tenjin-cli 0.1.0-alpha.1 → 0.1.0-alpha.10
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/NOTICE.md +33 -0
- package/README.md +572 -79
- package/dist/{_esm-ZH2J4QEH.js → _esm-C5CRWCYU.js} +2 -2
- package/dist/_esm-N4KAVXQR.js +881 -0
- package/dist/buy-FMDBZ4NY.js +44 -0
- package/dist/candidate-7LAELUQD.js +23 -0
- package/dist/ccip-RPPPKTJR.js +19 -0
- package/dist/{ccip-UCLT5VOW.js → ccip-ZGGWQN4X.js} +6 -5
- package/dist/chunk-2GSRYTZS.js +127 -0
- package/dist/chunk-2GSRYTZS.js.map +1 -0
- package/dist/chunk-2I4QTOLB.js +11 -0
- package/dist/chunk-2I4QTOLB.js.map +1 -0
- package/dist/chunk-36X2CA3N.js +311 -0
- package/dist/chunk-36X2CA3N.js.map +1 -0
- package/dist/{chunk-BRJHUQSY.js → chunk-47PP7TAG.js} +908 -812
- package/dist/chunk-47PP7TAG.js.map +1 -0
- package/dist/chunk-5JMKIDMM.js +316 -0
- package/dist/chunk-5JMKIDMM.js.map +1 -0
- package/dist/chunk-5JXAZP7H.js +206 -0
- package/dist/chunk-5JXAZP7H.js.map +1 -0
- package/dist/chunk-5SE6BJRP.js +135 -0
- package/dist/chunk-5SE6BJRP.js.map +1 -0
- package/dist/chunk-6BZLSRNU.js +149 -0
- package/dist/chunk-6BZLSRNU.js.map +1 -0
- package/dist/{chunk-IPOWB3G3.js → chunk-7FK2UN2T.js} +3515 -507
- package/dist/chunk-7FK2UN2T.js.map +1 -0
- package/dist/chunk-7WDY4AXV.js +14620 -0
- package/dist/chunk-7WDY4AXV.js.map +1 -0
- package/dist/chunk-A6KCZPNQ.js +83 -0
- package/dist/chunk-A6KCZPNQ.js.map +1 -0
- package/dist/chunk-AWQ6A4CI.js +341 -0
- package/dist/chunk-AWQ6A4CI.js.map +1 -0
- package/dist/chunk-BJJ5BQO6.js +162 -0
- package/dist/chunk-BJJ5BQO6.js.map +1 -0
- package/dist/chunk-BUDHTDKL.js +612 -0
- package/dist/chunk-BUDHTDKL.js.map +1 -0
- package/dist/chunk-DKQMJTG7.js +188 -0
- package/dist/chunk-DKQMJTG7.js.map +1 -0
- package/dist/chunk-FKSAUOJU.js +137 -0
- package/dist/chunk-FKSAUOJU.js.map +1 -0
- package/dist/{chunk-EXBMF5X7.js → chunk-GECSWJ7O.js} +526 -79
- package/dist/chunk-GECSWJ7O.js.map +1 -0
- package/dist/chunk-GSDZRCGF.js +105 -0
- package/dist/chunk-GSDZRCGF.js.map +1 -0
- package/dist/chunk-JSSIMGQT.js +174 -0
- package/dist/chunk-JSSIMGQT.js.map +1 -0
- package/dist/chunk-KYH4KPE5.js +1357 -0
- package/dist/chunk-KYH4KPE5.js.map +1 -0
- package/dist/chunk-KYQVEKP5.js +209 -0
- package/dist/chunk-KYQVEKP5.js.map +1 -0
- package/dist/chunk-KZAAWQNP.js +6199 -0
- package/dist/chunk-KZAAWQNP.js.map +1 -0
- package/dist/{chunk-T4LKNY7T.js → chunk-M2O56UK7.js} +225 -70
- package/dist/chunk-M2O56UK7.js.map +1 -0
- package/dist/chunk-MD7WGYYI.js +125 -0
- package/dist/chunk-MD7WGYYI.js.map +1 -0
- package/dist/chunk-MJZZTKCC.js +323 -0
- package/dist/chunk-MJZZTKCC.js.map +1 -0
- package/dist/chunk-O6CAUZGY.js +317 -0
- package/dist/chunk-O6CAUZGY.js.map +1 -0
- package/dist/chunk-P74I3WH4.js +204 -0
- package/dist/chunk-P74I3WH4.js.map +1 -0
- package/dist/chunk-POF7HPRV.js +145 -0
- package/dist/chunk-POF7HPRV.js.map +1 -0
- package/dist/chunk-POJRB2AE.js +83 -0
- package/dist/chunk-POJRB2AE.js.map +1 -0
- package/dist/{chunk-YG2DO46P.js → chunk-PZRAAAY2.js} +107 -22
- package/dist/chunk-PZRAAAY2.js.map +1 -0
- package/dist/chunk-PZSUWDF2.js +35 -0
- package/dist/chunk-PZSUWDF2.js.map +1 -0
- package/dist/chunk-QW2Q2KAH.js +27 -0
- package/dist/chunk-QW2Q2KAH.js.map +1 -0
- package/dist/chunk-R2VLGNFD.js +181 -0
- package/dist/chunk-R2VLGNFD.js.map +1 -0
- package/dist/{chunk-CUWUHTIL.js → chunk-RBJPAZFI.js} +16 -202
- package/dist/chunk-RBJPAZFI.js.map +1 -0
- package/dist/chunk-S5RYMCV6.js +70 -0
- package/dist/chunk-S5RYMCV6.js.map +1 -0
- package/dist/chunk-SGK2B724.js +67 -0
- package/dist/chunk-SGK2B724.js.map +1 -0
- package/dist/chunk-STND72DS.js +242 -0
- package/dist/chunk-STND72DS.js.map +1 -0
- package/dist/chunk-TEL27PR5.js +124 -0
- package/dist/chunk-TEL27PR5.js.map +1 -0
- package/dist/chunk-TWRYSGAW.js +134 -0
- package/dist/chunk-TWRYSGAW.js.map +1 -0
- package/dist/{chunk-LPRVHM7P.js → chunk-U5S527PP.js} +1655 -114
- package/dist/chunk-U5S527PP.js.map +1 -0
- package/dist/chunk-UHTVXQ2O.js +140 -0
- package/dist/chunk-UHTVXQ2O.js.map +1 -0
- package/dist/chunk-UOJRKQTZ.js +213 -0
- package/dist/chunk-UOJRKQTZ.js.map +1 -0
- package/dist/chunk-V4WWTZHZ.js +233 -0
- package/dist/chunk-V4WWTZHZ.js.map +1 -0
- package/dist/chunk-VRRLTZ2Q.js +651 -0
- package/dist/chunk-VRRLTZ2Q.js.map +1 -0
- package/dist/{chunk-Q53IYV2G.js → chunk-W6R3HAAG.js} +20 -17
- package/dist/{chunk-Q53IYV2G.js.map → chunk-W6R3HAAG.js.map} +1 -1
- package/dist/chunk-X3OOVSPX.js +154 -0
- package/dist/chunk-X3OOVSPX.js.map +1 -0
- package/dist/chunk-XJN5WUKL.js +204 -0
- package/dist/chunk-XJN5WUKL.js.map +1 -0
- package/dist/{chunk-DXPYFVKG.js → chunk-Y7ERTA7D.js} +35 -15
- package/dist/chunk-Y7ERTA7D.js.map +1 -0
- package/dist/chunk-YLYINX2H.js +7806 -0
- package/dist/chunk-YLYINX2H.js.map +1 -0
- package/dist/chunk-ZQIQ55KK.js +51 -0
- package/dist/chunk-ZQIQ55KK.js.map +1 -0
- package/dist/chunk-ZUAQRIVP.js +1369 -0
- package/dist/chunk-ZUAQRIVP.js.map +1 -0
- package/dist/{chunk-3IMLRUZE.js → chunk-ZXTAQYNA.js} +6 -2
- package/dist/chunk-ZXTAQYNA.js.map +1 -0
- package/dist/{cli-WA65NP4Y.js → cli-HK2XAWNW.js} +440 -175
- package/dist/cli-HK2XAWNW.js.map +1 -0
- package/dist/config-LYCHHNAJ.js +26 -0
- package/dist/config-LYCHHNAJ.js.map +1 -0
- package/dist/dist-U4M6QCKE.js +2842 -0
- package/dist/dist-U4M6QCKE.js.map +1 -0
- package/dist/doctor-2KPUQURC.js +27 -0
- package/dist/doctor-2KPUQURC.js.map +1 -0
- package/dist/edit-TST3OCKQ.js +38 -0
- package/dist/edit-TST3OCKQ.js.map +1 -0
- package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js +18 -0
- package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/inspect-TPTHVPBB.js +35 -0
- package/dist/inspect-TPTHVPBB.js.map +1 -0
- package/dist/install-PT3XEDJ6.js +1869 -0
- package/dist/install-PT3XEDJ6.js.map +1 -0
- package/dist/{mine.wasm-GQECMSGN.js → mine.wasm-6PIT3DK6.js} +2 -2
- package/dist/outcome-NPNSF2Q7.js +22 -0
- package/dist/outcome-NPNSF2Q7.js.map +1 -0
- package/dist/publish-XP5SEWST.js +41 -0
- package/dist/publish-XP5SEWST.js.map +1 -0
- package/dist/read-D4VXRWOG.js +158 -0
- package/dist/read-D4VXRWOG.js.map +1 -0
- package/dist/run-3IPGEXW7.js +16902 -0
- package/dist/run-3IPGEXW7.js.map +1 -0
- package/dist/search-YOBD6VDI.js +24 -0
- package/dist/search-YOBD6VDI.js.map +1 -0
- package/dist/{secp256k1-BEZS642W.js → secp256k1-XRPVBC6V.js} +5 -4
- package/dist/secp256k1-XRPVBC6V.js.map +1 -0
- package/dist/send-BWNP6WN4.js +223 -0
- package/dist/send-BWNP6WN4.js.map +1 -0
- package/dist/session-GZEZBOMI.js +88 -0
- package/dist/session-GZEZBOMI.js.map +1 -0
- package/dist/skill-heal-OK6YALW6.js +85 -0
- package/dist/skill-heal-OK6YALW6.js.map +1 -0
- package/dist/usdc-4VCDHFWX.js +38 -0
- package/dist/usdc-4VCDHFWX.js.map +1 -0
- package/dist/viemAdapter-By13KInL-TUQJBMHM.js +14 -0
- package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
- package/dist/wallet-5RHDFPN2.js +32 -0
- package/dist/wallet-5RHDFPN2.js.map +1 -0
- package/dist/wallet-YEGQBWWL.js +42 -0
- package/dist/wallet-YEGQBWWL.js.map +1 -0
- package/docs/agent-permissions.md +281 -0
- package/package.json +25 -18
- package/skills/tenjin/SKILL.md +364 -0
- package/skills/tenjin-publish/SKILL.md +219 -0
- package/skills/tenjin-search/SKILL.md +335 -0
- package/dist/chunk-BRJHUQSY.js.map +0 -1
- package/dist/chunk-CUWUHTIL.js.map +0 -1
- package/dist/chunk-DXPYFVKG.js.map +0 -1
- package/dist/chunk-EXBMF5X7.js.map +0 -1
- package/dist/chunk-EZROUI5U.js +0 -135
- package/dist/chunk-EZROUI5U.js.map +0 -1
- package/dist/chunk-IPOWB3G3.js.map +0 -1
- package/dist/chunk-LPRVHM7P.js.map +0 -1
- package/dist/chunk-T4LKNY7T.js.map +0 -1
- package/dist/chunk-YBMMV4Y4.js +0 -51
- package/dist/chunk-YBMMV4Y4.js.map +0 -1
- package/dist/chunk-YG2DO46P.js.map +0 -1
- package/dist/chunk-ZPZFPVDN.js +0 -67
- package/dist/chunk-ZPZFPVDN.js.map +0 -1
- package/dist/cli-WA65NP4Y.js.map +0 -1
- package/dist/config-CEFTL5ZL.js +0 -164
- package/dist/config-CEFTL5ZL.js.map +0 -1
- package/dist/doctor-3QBYN46N.js +0 -338
- package/dist/doctor-3QBYN46N.js.map +0 -1
- package/dist/usdc-44R6XZF2.js +0 -18
- package/dist/wallet-ELBTBMXO.js +0 -20
- package/dist/wallet-XD576HF3.js +0 -173
- package/dist/wallet-XD576HF3.js.map +0 -1
- /package/dist/{_esm-ZH2J4QEH.js.map → _esm-C5CRWCYU.js.map} +0 -0
- /package/dist/{ccip-UCLT5VOW.js.map → _esm-N4KAVXQR.js.map} +0 -0
- /package/dist/{chunk-3IMLRUZE.js.map → buy-FMDBZ4NY.js.map} +0 -0
- /package/dist/{secp256k1-BEZS642W.js.map → candidate-7LAELUQD.js.map} +0 -0
- /package/dist/{usdc-44R6XZF2.js.map → ccip-RPPPKTJR.js.map} +0 -0
- /package/dist/{wallet-ELBTBMXO.js.map → ccip-ZGGWQN4X.js.map} +0 -0
- /package/dist/{mine.wasm-GQECMSGN.js.map → mine.wasm-6PIT3DK6.js.map} +0 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
createPublicClient,
|
|
4
|
+
defineBlock,
|
|
5
|
+
defineChain,
|
|
6
|
+
defineTransaction,
|
|
7
|
+
defineTransactionReceipt,
|
|
8
|
+
formatTransaction,
|
|
9
|
+
http
|
|
10
|
+
} from "./chunk-7FK2UN2T.js";
|
|
11
|
+
import {
|
|
12
|
+
serializeTransaction,
|
|
13
|
+
toRlp
|
|
14
|
+
} from "./chunk-M2O56UK7.js";
|
|
15
|
+
import {
|
|
16
|
+
decodeFunctionData,
|
|
17
|
+
encodeFunctionData,
|
|
18
|
+
erc20Abi
|
|
19
|
+
} from "./chunk-U5S527PP.js";
|
|
20
|
+
import {
|
|
21
|
+
InvalidAddressError,
|
|
22
|
+
concatHex,
|
|
23
|
+
hexToBigInt,
|
|
24
|
+
hexToNumber,
|
|
25
|
+
isAddress,
|
|
26
|
+
toHex
|
|
27
|
+
} from "./chunk-47PP7TAG.js";
|
|
28
|
+
|
|
29
|
+
// node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/op-stack/contracts.js
|
|
30
|
+
var contracts = {
|
|
31
|
+
gasPriceOracle: { address: "0x420000000000000000000000000000000000000F" },
|
|
32
|
+
l1Block: { address: "0x4200000000000000000000000000000000000015" },
|
|
33
|
+
l2CrossDomainMessenger: {
|
|
34
|
+
address: "0x4200000000000000000000000000000000000007"
|
|
35
|
+
},
|
|
36
|
+
l2Erc721Bridge: { address: "0x4200000000000000000000000000000000000014" },
|
|
37
|
+
l2StandardBridge: { address: "0x4200000000000000000000000000000000000010" },
|
|
38
|
+
l2ToL1MessagePasser: {
|
|
39
|
+
address: "0x4200000000000000000000000000000000000016"
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/op-stack/formatters.js
|
|
44
|
+
var formatters = {
|
|
45
|
+
block: /* @__PURE__ */ defineBlock({
|
|
46
|
+
format(args) {
|
|
47
|
+
const transactions = args.transactions?.map((transaction) => {
|
|
48
|
+
if (typeof transaction === "string")
|
|
49
|
+
return transaction;
|
|
50
|
+
const formatted = formatTransaction(transaction);
|
|
51
|
+
if (formatted.typeHex === "0x7e") {
|
|
52
|
+
formatted.isSystemTx = transaction.isSystemTx;
|
|
53
|
+
formatted.mint = transaction.mint ? hexToBigInt(transaction.mint) : void 0;
|
|
54
|
+
formatted.sourceHash = transaction.sourceHash;
|
|
55
|
+
formatted.type = "deposit";
|
|
56
|
+
}
|
|
57
|
+
return formatted;
|
|
58
|
+
});
|
|
59
|
+
return {
|
|
60
|
+
transactions,
|
|
61
|
+
stateRoot: args.stateRoot
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
}),
|
|
65
|
+
transaction: /* @__PURE__ */ defineTransaction({
|
|
66
|
+
format(args) {
|
|
67
|
+
const transaction = {};
|
|
68
|
+
if (args.type === "0x7e") {
|
|
69
|
+
transaction.isSystemTx = args.isSystemTx;
|
|
70
|
+
transaction.mint = args.mint ? hexToBigInt(args.mint) : void 0;
|
|
71
|
+
transaction.sourceHash = args.sourceHash;
|
|
72
|
+
transaction.type = "deposit";
|
|
73
|
+
}
|
|
74
|
+
return transaction;
|
|
75
|
+
}
|
|
76
|
+
}),
|
|
77
|
+
transactionReceipt: /* @__PURE__ */ defineTransactionReceipt({
|
|
78
|
+
format(args) {
|
|
79
|
+
return {
|
|
80
|
+
...args.depositNonce ? { depositNonce: hexToBigInt(args.depositNonce) } : {},
|
|
81
|
+
...args.depositReceiptVersion ? { depositReceiptVersion: hexToNumber(args.depositReceiptVersion) } : {},
|
|
82
|
+
l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,
|
|
83
|
+
l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,
|
|
84
|
+
l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,
|
|
85
|
+
l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/op-stack/serializers.js
|
|
92
|
+
function serializeTransaction2(transaction, signature) {
|
|
93
|
+
if (isDeposit(transaction))
|
|
94
|
+
return serializeTransactionDeposit(transaction);
|
|
95
|
+
return serializeTransaction(transaction, signature);
|
|
96
|
+
}
|
|
97
|
+
var serializers = {
|
|
98
|
+
transaction: serializeTransaction2
|
|
99
|
+
};
|
|
100
|
+
function serializeTransactionDeposit(transaction) {
|
|
101
|
+
assertTransactionDeposit(transaction);
|
|
102
|
+
const { sourceHash, data, from, gas, isSystemTx, mint, to, value } = transaction;
|
|
103
|
+
const serializedTransaction = [
|
|
104
|
+
sourceHash,
|
|
105
|
+
from,
|
|
106
|
+
to ?? "0x",
|
|
107
|
+
mint ? toHex(mint) : "0x",
|
|
108
|
+
value ? toHex(value) : "0x",
|
|
109
|
+
gas ? toHex(gas) : "0x",
|
|
110
|
+
isSystemTx ? "0x1" : "0x",
|
|
111
|
+
data ?? "0x"
|
|
112
|
+
];
|
|
113
|
+
return concatHex([
|
|
114
|
+
"0x7e",
|
|
115
|
+
toRlp(serializedTransaction)
|
|
116
|
+
]);
|
|
117
|
+
}
|
|
118
|
+
function isDeposit(transaction) {
|
|
119
|
+
if (transaction.type === "deposit")
|
|
120
|
+
return true;
|
|
121
|
+
if (typeof transaction.sourceHash !== "undefined")
|
|
122
|
+
return true;
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
function assertTransactionDeposit(transaction) {
|
|
126
|
+
const { from, to } = transaction;
|
|
127
|
+
if (from && !isAddress(from))
|
|
128
|
+
throw new InvalidAddressError({ address: from });
|
|
129
|
+
if (to && !isAddress(to))
|
|
130
|
+
throw new InvalidAddressError({ address: to });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/op-stack/chainConfig.js
|
|
134
|
+
var chainConfig = {
|
|
135
|
+
blockTime: 2e3,
|
|
136
|
+
contracts,
|
|
137
|
+
formatters,
|
|
138
|
+
serializers
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
// node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/chains/definitions/base.js
|
|
142
|
+
var sourceId = 1;
|
|
143
|
+
var base = /* @__PURE__ */ defineChain({
|
|
144
|
+
...chainConfig,
|
|
145
|
+
id: 8453,
|
|
146
|
+
name: "Base",
|
|
147
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
148
|
+
rpcUrls: {
|
|
149
|
+
default: {
|
|
150
|
+
http: ["https://mainnet.base.org"]
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
blockExplorers: {
|
|
154
|
+
default: {
|
|
155
|
+
name: "Basescan",
|
|
156
|
+
url: "https://basescan.org",
|
|
157
|
+
apiUrl: "https://api.basescan.org/api"
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
contracts: {
|
|
161
|
+
...chainConfig.contracts,
|
|
162
|
+
disputeGameFactory: {
|
|
163
|
+
[sourceId]: {
|
|
164
|
+
address: "0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
l2OutputOracle: {
|
|
168
|
+
[sourceId]: {
|
|
169
|
+
address: "0x56315b90c40730925ec5485cf004d835058518A0"
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
multicall3: {
|
|
173
|
+
address: "0xca11bde05977b3631167028862be2a173976ca11",
|
|
174
|
+
blockCreated: 5022
|
|
175
|
+
},
|
|
176
|
+
portal: {
|
|
177
|
+
[sourceId]: {
|
|
178
|
+
address: "0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",
|
|
179
|
+
blockCreated: 17482143
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
l1StandardBridge: {
|
|
183
|
+
[sourceId]: {
|
|
184
|
+
address: "0x3154Cf16ccdb4C6d922629664174b904d80F2C35",
|
|
185
|
+
blockCreated: 17482143
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
sourceId
|
|
190
|
+
});
|
|
191
|
+
var basePreconf = /* @__PURE__ */ defineChain({
|
|
192
|
+
...base,
|
|
193
|
+
experimental_preconfirmationTime: 200,
|
|
194
|
+
rpcUrls: {
|
|
195
|
+
default: {
|
|
196
|
+
http: ["https://mainnet-preconf.base.org"]
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
// src/lib/usdc.ts
|
|
202
|
+
var USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
|
|
203
|
+
var USDC_DECIMALS = 6;
|
|
204
|
+
async function getUsdcBalance(address, rpcUrl) {
|
|
205
|
+
const client = createPublicClient({ chain: base, transport: http(rpcUrl) });
|
|
206
|
+
return client.readContract({
|
|
207
|
+
address: USDC_ADDRESS,
|
|
208
|
+
abi: erc20Abi,
|
|
209
|
+
functionName: "balanceOf",
|
|
210
|
+
args: [address]
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
var SEND_GAS_CAP = 150000n;
|
|
214
|
+
var SEND_MAX_FEE_PER_GAS_CAP = 10000000000n;
|
|
215
|
+
var SEND_MAX_PRIORITY_FEE_CAP = 2000000000n;
|
|
216
|
+
var FeeCapExceededError = class extends Error {
|
|
217
|
+
constructor(field, value, cap) {
|
|
218
|
+
super(`${field} estimate ${value} exceeds the send ceiling ${cap}`);
|
|
219
|
+
this.name = "FeeCapExceededError";
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
var SendRevertedError = class extends Error {
|
|
223
|
+
constructor(txHash) {
|
|
224
|
+
super(`Transaction ${txHash} reverted`);
|
|
225
|
+
this.txHash = txHash;
|
|
226
|
+
this.name = "SendRevertedError";
|
|
227
|
+
}
|
|
228
|
+
txHash;
|
|
229
|
+
};
|
|
230
|
+
var SendPendingError = class extends Error {
|
|
231
|
+
constructor(txHash) {
|
|
232
|
+
super(`Transaction ${txHash} was broadcast but not confirmed in time`);
|
|
233
|
+
this.txHash = txHash;
|
|
234
|
+
this.name = "SendPendingError";
|
|
235
|
+
}
|
|
236
|
+
txHash;
|
|
237
|
+
};
|
|
238
|
+
async function prepareUsdcSend({
|
|
239
|
+
from,
|
|
240
|
+
to,
|
|
241
|
+
amountAtomic,
|
|
242
|
+
rpcUrl
|
|
243
|
+
}) {
|
|
244
|
+
const client = createPublicClient({ chain: base, transport: http(rpcUrl) });
|
|
245
|
+
const data = encodeFunctionData({
|
|
246
|
+
abi: erc20Abi,
|
|
247
|
+
functionName: "transfer",
|
|
248
|
+
args: [to, amountAtomic]
|
|
249
|
+
});
|
|
250
|
+
const [nonce, gas, fees, ethBalanceWei] = await Promise.all([
|
|
251
|
+
client.getTransactionCount({ address: from, blockTag: "pending" }),
|
|
252
|
+
client.estimateGas({ account: from, to: USDC_ADDRESS, data }),
|
|
253
|
+
client.estimateFeesPerGas(),
|
|
254
|
+
client.getBalance({ address: from })
|
|
255
|
+
]);
|
|
256
|
+
assertUnderCap("gas", gas, SEND_GAS_CAP);
|
|
257
|
+
assertUnderCap("maxFeePerGas", fees.maxFeePerGas, SEND_MAX_FEE_PER_GAS_CAP);
|
|
258
|
+
assertUnderCap("maxPriorityFeePerGas", fees.maxPriorityFeePerGas, SEND_MAX_PRIORITY_FEE_CAP);
|
|
259
|
+
return {
|
|
260
|
+
to,
|
|
261
|
+
amountAtomic,
|
|
262
|
+
data,
|
|
263
|
+
nonce,
|
|
264
|
+
gas,
|
|
265
|
+
maxFeePerGas: fees.maxFeePerGas,
|
|
266
|
+
maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
|
|
267
|
+
feeWei: gas * fees.maxFeePerGas,
|
|
268
|
+
ethBalanceWei
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
async function broadcastUsdcSend({
|
|
272
|
+
signer,
|
|
273
|
+
prepared,
|
|
274
|
+
rpcUrl,
|
|
275
|
+
receiptTimeoutMs = 12e4
|
|
276
|
+
}) {
|
|
277
|
+
const client = createPublicClient({ chain: base, transport: http(rpcUrl) });
|
|
278
|
+
const decoded = decodeFunctionData({ abi: erc20Abi, data: prepared.data });
|
|
279
|
+
if (decoded.functionName !== "transfer" || decoded.args[0].toLowerCase() !== prepared.to.toLowerCase() || decoded.args[1] !== prepared.amountAtomic) {
|
|
280
|
+
throw new Error(
|
|
281
|
+
"Prepared calldata does not decode to the previewed recipient and amount; nothing was signed."
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
const serializedTransaction = await signer.signTransaction({
|
|
285
|
+
type: "eip1559",
|
|
286
|
+
chainId: base.id,
|
|
287
|
+
to: USDC_ADDRESS,
|
|
288
|
+
// Explicitly zero: an ERC-20 transfer carries no native value (test-pinned).
|
|
289
|
+
value: 0n,
|
|
290
|
+
data: prepared.data,
|
|
291
|
+
nonce: prepared.nonce,
|
|
292
|
+
gas: prepared.gas,
|
|
293
|
+
maxFeePerGas: prepared.maxFeePerGas,
|
|
294
|
+
maxPriorityFeePerGas: prepared.maxPriorityFeePerGas
|
|
295
|
+
});
|
|
296
|
+
const txHash = await client.sendRawTransaction({ serializedTransaction });
|
|
297
|
+
let receipt;
|
|
298
|
+
try {
|
|
299
|
+
receipt = await client.waitForTransactionReceipt({ hash: txHash, timeout: receiptTimeoutMs });
|
|
300
|
+
} catch {
|
|
301
|
+
throw new SendPendingError(txHash);
|
|
302
|
+
}
|
|
303
|
+
if (receipt.status !== "success") throw new SendRevertedError(txHash);
|
|
304
|
+
return txHash;
|
|
305
|
+
}
|
|
306
|
+
function assertUnderCap(field, value, cap) {
|
|
307
|
+
if (value > cap) throw new FeeCapExceededError(field, value, cap);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export {
|
|
311
|
+
USDC_ADDRESS,
|
|
312
|
+
USDC_DECIMALS,
|
|
313
|
+
getUsdcBalance,
|
|
314
|
+
SEND_GAS_CAP,
|
|
315
|
+
SEND_MAX_FEE_PER_GAS_CAP,
|
|
316
|
+
SEND_MAX_PRIORITY_FEE_CAP,
|
|
317
|
+
FeeCapExceededError,
|
|
318
|
+
SendRevertedError,
|
|
319
|
+
SendPendingError,
|
|
320
|
+
prepareUsdcSend,
|
|
321
|
+
broadcastUsdcSend
|
|
322
|
+
};
|
|
323
|
+
//# sourceMappingURL=chunk-MJZZTKCC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/contracts.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/formatters.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/serializers.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/op-stack/chainConfig.ts","../node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/chains/definitions/base.ts","../src/lib/usdc.ts"],"sourcesContent":["import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt, hexToNumber } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n ...(args.depositNonce\n ? { depositNonce: hexToBigInt(args.depositNonce) }\n : {}),\n ...(args.depositReceiptVersion\n ? { depositReceiptVersion: hexToNumber(args.depositReceiptVersion) }\n : {}),\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy<TransactionSerializableDeposit, 'type'> {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n} as const\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n})\n","import {\n createPublicClient,\n decodeFunctionData,\n encodeFunctionData,\n erc20Abi,\n http,\n type Address,\n type Hex,\n} from 'viem';\nimport { base } from 'viem/chains';\nimport type { TenjinSigner } from './wallet/provider';\n\n// Values mirror the app's lib/chain.ts Base mainnet entry (chain 8453).\nexport const USDC_ADDRESS: Address = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';\nexport const USDC_DECIMALS = 6;\n\nexport async function getUsdcBalance(address: Address, rpcUrl: string): Promise<bigint> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n return client.readContract({\n address: USDC_ADDRESS,\n abi: erc20Abi,\n functionName: 'balanceOf',\n args: [address],\n });\n}\n\n// The chain boundary for `tenjin send`, two-phase around the human confirm:\n// prepareUsdcSend (read-only: encode, nonce, gas, fees, ETH-for-gas balance)\n// runs BEFORE the confirm so the prompt can show the fee, broadcastUsdcSend\n// (sign via the TenjinSigner seam, broadcast, wait for the receipt) runs after.\n// Command tests mock this whole module, so no test can ever reach a real chain.\n\n/**\n * Ceilings on the RPC-supplied gas and fee fields. The RPC endpoint is\n * config-controlled and its estimates go straight into the signed transaction; a\n * hostile or broken endpoint returning huge values would burn the wallet's ETH\n * as fees. An ERC-20 transfer is ~65k gas and Base fees run well under a gwei,\n * so estimates past these bounds mean something is wrong: refuse, never clamp\n * (a clamped maxFeePerGas below the real base fee would just strand the tx).\n * A genuine extreme fee spike on Base trips the same refusal; that is intended\n * — waiting it out beats signing an irreversible transfer at panic prices.\n */\nexport const SEND_GAS_CAP = 150_000n;\nexport const SEND_MAX_FEE_PER_GAS_CAP = 10_000_000_000n; // 10 gwei\nexport const SEND_MAX_PRIORITY_FEE_CAP = 2_000_000_000n; // 2 gwei\n\n/** An RPC gas/fee estimate exceeded the send ceilings; nothing was signed. */\nexport class FeeCapExceededError extends Error {\n constructor(field: string, value: bigint, cap: bigint) {\n super(`${field} estimate ${value} exceeds the send ceiling ${cap}`);\n this.name = 'FeeCapExceededError';\n }\n}\n\n/** The transfer was mined but reverted; the fee was spent, the USDC did not move. */\nexport class SendRevertedError extends Error {\n constructor(readonly txHash: Hex) {\n super(`Transaction ${txHash} reverted`);\n this.name = 'SendRevertedError';\n }\n}\n\n/** Broadcast succeeded but no receipt arrived in time; the tx may still mine. */\nexport class SendPendingError extends Error {\n constructor(readonly txHash: Hex) {\n super(`Transaction ${txHash} was broadcast but not confirmed in time`);\n this.name = 'SendPendingError';\n }\n}\n\nexport interface PrepareUsdcSendArgs {\n from: Address;\n to: Address;\n amountAtomic: bigint;\n rpcUrl: string;\n}\n\n/**\n * Everything signed later, fixed at prepare time, plus the gas-cost preview.\n * The nonce is pinned here, BEFORE the human confirm, so anything else spending\n * from this key during that window makes the later broadcast fail nonce-stale\n * (an RPC_ERROR from the node; nothing double-spends — re-run to re-prepare).\n * `to` and `amountAtomic` are the previewed intent; broadcastUsdcSend re-decodes\n * `data` against them before signing.\n */\nexport interface PreparedUsdcSend {\n to: Address;\n amountAtomic: bigint;\n data: Hex;\n nonce: number;\n gas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n /** Worst-case fee (gas * maxFeePerGas), for the confirm prompt and gas check. */\n feeWei: bigint;\n /** The sender's native ETH balance, for the has-gas pre-check. */\n ethBalanceWei: bigint;\n}\n\nexport async function prepareUsdcSend({\n from,\n to,\n amountAtomic,\n rpcUrl,\n}: PrepareUsdcSendArgs): Promise<PreparedUsdcSend> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: 'transfer',\n args: [to, amountAtomic],\n });\n const [nonce, gas, fees, ethBalanceWei] = await Promise.all([\n client.getTransactionCount({ address: from, blockTag: 'pending' }),\n client.estimateGas({ account: from, to: USDC_ADDRESS, data }),\n client.estimateFeesPerGas(),\n client.getBalance({ address: from }),\n ]);\n assertUnderCap('gas', gas, SEND_GAS_CAP);\n assertUnderCap('maxFeePerGas', fees.maxFeePerGas, SEND_MAX_FEE_PER_GAS_CAP);\n assertUnderCap('maxPriorityFeePerGas', fees.maxPriorityFeePerGas, SEND_MAX_PRIORITY_FEE_CAP);\n return {\n to,\n amountAtomic,\n data,\n nonce,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n feeWei: gas * fees.maxFeePerGas,\n ethBalanceWei,\n };\n}\n\nexport interface BroadcastUsdcSendArgs {\n signer: TenjinSigner;\n prepared: PreparedUsdcSend;\n rpcUrl: string;\n /** Receipt wait bound in ms; Base blocks are ~2s, so the default is generous. */\n receiptTimeoutMs?: number;\n}\n\n/**\n * Sign the prepared transfer through the TenjinSigner seam (never a raw key),\n * broadcast it, and wait for the receipt so \"sent\" means mined. Throws\n * SendRevertedError (mined but failed) or SendPendingError (no receipt in time);\n * both carry the hash so the caller can report it either way.\n */\nexport async function broadcastUsdcSend({\n signer,\n prepared,\n rpcUrl,\n receiptTimeoutMs = 120_000,\n}: BroadcastUsdcSendArgs): Promise<Hex> {\n const client = createPublicClient({ chain: base, transport: http(rpcUrl) });\n // Pre-sign cross-check, the calldata twin of send.ts's signer/preview match:\n // the bytes about to be signed must still decode to the previewed recipient\n // and amount. Unreachable unless prepare-time state was corrupted; refusing\n // here means nothing is signed against a preview it does not match.\n const decoded = decodeFunctionData({ abi: erc20Abi, data: prepared.data });\n if (\n decoded.functionName !== 'transfer' ||\n decoded.args[0].toLowerCase() !== prepared.to.toLowerCase() ||\n decoded.args[1] !== prepared.amountAtomic\n ) {\n throw new Error(\n 'Prepared calldata does not decode to the previewed recipient and amount; nothing was signed.',\n );\n }\n const serializedTransaction = await signer.signTransaction({\n type: 'eip1559',\n chainId: base.id,\n to: USDC_ADDRESS,\n // Explicitly zero: an ERC-20 transfer carries no native value (test-pinned).\n value: 0n,\n data: prepared.data,\n nonce: prepared.nonce,\n gas: prepared.gas,\n maxFeePerGas: prepared.maxFeePerGas,\n maxPriorityFeePerGas: prepared.maxPriorityFeePerGas,\n });\n const txHash = await client.sendRawTransaction({ serializedTransaction });\n let receipt;\n try {\n receipt = await client.waitForTransactionReceipt({ hash: txHash, timeout: receiptTimeoutMs });\n } catch {\n throw new SendPendingError(txHash);\n }\n if (receipt.status !== 'success') throw new SendRevertedError(txHash);\n return txHash;\n}\n\nfunction assertUnderCap(field: string, value: bigint, cap: bigint): void {\n if (value > cap) throw new FeeCapExceededError(field, value, cap);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMO,IAAM,YAAY;EACvB,gBAAgB,EAAE,SAAS,6CA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AO,gBAAgB;AAAA,IACzD,MAAM;AAAA,IACN,SAAS,KAAK;AAAA,IACd,IAAI;AAAA;AAAA,IAEJ,OAAO;AAAA,IACP,MAAM,SAAS;AAAA,IACf,OAAO,SAAS;AAAA,IAChB,KAAK,SAAS;AAAA,IACd,cAAc,SAAS;AAAA,IACvB,sBAAsB,SAAS;AAAA,EACjC,CAAC;AACD,QAAM,SAAS,MAAM,OAAO,mBAAmB,EAAE,sBAAsB,CAAC;AACxE,MAAI;AACJ,MAAI;AACF,cAAU,MAAM,OAAO,0BAA0B,EAAE,MAAM,QAAQ,SAAS,iBAAiB,CAAC;AAAA,EAC9F,QAAQ;AACN,UAAM,IAAI,iBAAiB,MAAM;AAAA,EACnC;AACA,MAAI,QAAQ,WAAW,UAAW,OAAM,IAAI,kBAAkB,MAAM;AACpE,SAAO;AACT;AAEA,SAAS,eAAe,OAAe,OAAe,KAAmB;AACvE,MAAI,QAAQ,IAAK,OAAM,IAAI,oBAAoB,OAAO,OAAO,GAAG;AAClE;","names":["serializeTransaction"]}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
httpRequest
|
|
4
|
+
} from "./chunk-DKQMJTG7.js";
|
|
5
|
+
import {
|
|
6
|
+
trimSlash
|
|
7
|
+
} from "./chunk-PZSUWDF2.js";
|
|
8
|
+
import {
|
|
9
|
+
ATOMIC_RE,
|
|
10
|
+
UUID_RE
|
|
11
|
+
} from "./chunk-36X2CA3N.js";
|
|
12
|
+
import {
|
|
13
|
+
CliError,
|
|
14
|
+
external_exports
|
|
15
|
+
} from "./chunk-PZRAAAY2.js";
|
|
16
|
+
|
|
17
|
+
// src/lib/agent-api.ts
|
|
18
|
+
var FRESH_WITHIN_RE = /^P(\d+)[DWMY]$/;
|
|
19
|
+
var CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;
|
|
20
|
+
var MAX_LIMIT = 10;
|
|
21
|
+
function buildSearchRequest(input) {
|
|
22
|
+
const question = input.question.trim();
|
|
23
|
+
if (question.length === 0 || question.length > 512) {
|
|
24
|
+
throw new CliError("USAGE", "question must be 1 to 512 characters", {
|
|
25
|
+
fix: "Pass a non-empty question under 512 characters."
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
if (input.freshWithin !== void 0) {
|
|
29
|
+
const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];
|
|
30
|
+
if (digits === void 0 || Number(digits) === 0) {
|
|
31
|
+
throw new CliError("USAGE", `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {
|
|
32
|
+
fix: "Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y."
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (input.maxPrice !== void 0 && !ATOMIC_RE.test(input.maxPrice)) {
|
|
37
|
+
throw new CliError("USAGE", `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {
|
|
38
|
+
fix: "Pass an atomic USDC integer, e.g. 100000 for $0.10."
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const limit = input.limit ?? 5;
|
|
42
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
43
|
+
throw new CliError("USAGE", `Invalid --limit: ${JSON.stringify(input.limit)}`, {
|
|
44
|
+
fix: `Pass an integer between 1 and ${MAX_LIMIT}.`
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if (input.appliesTo !== void 0) {
|
|
48
|
+
const keys = Object.keys(input.appliesTo);
|
|
49
|
+
if (keys.length > 8) {
|
|
50
|
+
throw new CliError("USAGE", "Too many --applies-to keys (max 8).");
|
|
51
|
+
}
|
|
52
|
+
for (const [key, values] of Object.entries(input.appliesTo)) {
|
|
53
|
+
if (!CANONICAL_KEY_RE.test(key)) {
|
|
54
|
+
throw new CliError("USAGE", `Invalid appliesTo key: ${JSON.stringify(key)}`, {
|
|
55
|
+
fix: "Keys must be canonical lowercase identifiers, e.g. products=Vercel."
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (values.length === 0) {
|
|
59
|
+
throw new CliError("USAGE", `appliesTo key ${JSON.stringify(key)} has no values`, {
|
|
60
|
+
fix: "Give each --applies-to key at least one value."
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
if (values.length > 20) {
|
|
64
|
+
throw new CliError("USAGE", `Too many --applies-to values for ${key} (max 20).`);
|
|
65
|
+
}
|
|
66
|
+
for (const value of values) {
|
|
67
|
+
if (value.length === 0 || value.length > 120) {
|
|
68
|
+
throw new CliError(
|
|
69
|
+
"USAGE",
|
|
70
|
+
`Invalid --applies-to value for ${key}: must be 1 to 120 characters.`
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
schemaVersion: 2,
|
|
78
|
+
question,
|
|
79
|
+
...input.freshWithin !== void 0 ? { freshWithin: input.freshWithin } : {},
|
|
80
|
+
...input.maxPrice !== void 0 ? { maxPrice: input.maxPrice } : {},
|
|
81
|
+
...input.appliesTo !== void 0 ? { appliesTo: input.appliesTo } : {},
|
|
82
|
+
limit
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
var searchCandidateSchema = external_exports.object({
|
|
86
|
+
resourceId: external_exports.string().regex(UUID_RE, "resourceId must be a uuid"),
|
|
87
|
+
url: external_exports.string(),
|
|
88
|
+
slug: external_exports.string(),
|
|
89
|
+
title: external_exports.string(),
|
|
90
|
+
artifactType: external_exports.string(),
|
|
91
|
+
price: external_exports.string().regex(ATOMIC_RE, "price must be an atomic integer string"),
|
|
92
|
+
asOf: external_exports.string().nullable(),
|
|
93
|
+
validUntil: external_exports.string().nullable(),
|
|
94
|
+
matchReasons: external_exports.array(external_exports.string()),
|
|
95
|
+
estimatedTokens: external_exports.number(),
|
|
96
|
+
creator: external_exports.object({ handle: external_exports.string() }).passthrough()
|
|
97
|
+
}).passthrough();
|
|
98
|
+
var BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 };
|
|
99
|
+
var searchBrowseSchema = external_exports.object({
|
|
100
|
+
resourceId: external_exports.string().regex(UUID_RE, "resourceId must be a uuid"),
|
|
101
|
+
url: external_exports.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),
|
|
102
|
+
title: external_exports.string(),
|
|
103
|
+
price: external_exports.string().regex(ATOMIC_RE, "price must be an atomic integer string"),
|
|
104
|
+
creator: external_exports.object({ handle: external_exports.string() }).passthrough()
|
|
105
|
+
}).passthrough();
|
|
106
|
+
var searchResponseSchema = external_exports.object({
|
|
107
|
+
schemaVersion: external_exports.literal(2),
|
|
108
|
+
searchId: external_exports.string().regex(UUID_RE, "searchId must be a uuid"),
|
|
109
|
+
decision: external_exports.enum(["CANDIDATES", "MISS"]),
|
|
110
|
+
calibration: external_exports.string(),
|
|
111
|
+
candidates: external_exports.array(searchCandidateSchema).optional(),
|
|
112
|
+
// Set only when the server's size backstop dropped trailing candidates the
|
|
113
|
+
// requested limit had room for; omitted entirely otherwise. There is no cursor,
|
|
114
|
+
// so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales
|
|
115
|
+
// with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what
|
|
116
|
+
// recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the
|
|
117
|
+
// question is the remedy. `runSearch` picks the half that applies.
|
|
118
|
+
truncated: external_exports.literal(true).optional(),
|
|
119
|
+
// Omitted entirely by the server when empty, and only ever present on a MISS.
|
|
120
|
+
// Not enforced here (a stricter schema would reject an otherwise-usable
|
|
121
|
+
// response); truncateResponse drops it on a CANDIDATES decision instead.
|
|
122
|
+
browse: external_exports.array(searchBrowseSchema).optional()
|
|
123
|
+
});
|
|
124
|
+
function apiFailure(url, result) {
|
|
125
|
+
const code = result.kind === "network" || result.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
|
|
126
|
+
return new CliError(code, `${url}: ${result.message}`, {
|
|
127
|
+
fix: "Check your network and the configured base URL (`tenjin config get baseUrl`), then retry."
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
function rateLimitError(url, header) {
|
|
131
|
+
const retryAfter = header("retry-after");
|
|
132
|
+
const seconds = retryAfter !== void 0 ? Number(retryAfter) : void 0;
|
|
133
|
+
return new CliError("RATE_LIMITED", `${url}: rate limited by the server.`, {
|
|
134
|
+
fix: seconds !== void 0 && Number.isFinite(seconds) ? `Retry after ${seconds}s.` : "Back off and retry shortly.",
|
|
135
|
+
details: {
|
|
136
|
+
...seconds !== void 0 && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
function serverErrorMessage(json) {
|
|
141
|
+
if (typeof json === "object" && json !== null) {
|
|
142
|
+
const rec = json;
|
|
143
|
+
const err = rec.error;
|
|
144
|
+
if (typeof err === "string") return err;
|
|
145
|
+
if (typeof err === "object" && err !== null) {
|
|
146
|
+
const m = err.message;
|
|
147
|
+
if (typeof m === "string") return m;
|
|
148
|
+
}
|
|
149
|
+
if (typeof rec.message === "string") return rec.message;
|
|
150
|
+
}
|
|
151
|
+
return void 0;
|
|
152
|
+
}
|
|
153
|
+
async function postSearch(body, opts) {
|
|
154
|
+
const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;
|
|
155
|
+
const res = await httpRequest(url, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
timeoutMs: opts.timeoutMs,
|
|
158
|
+
headers: opts.evalCohort === true ? { "x-tenjin-eval-cohort": "1" } : {},
|
|
159
|
+
jsonBody: body,
|
|
160
|
+
fetchImpl: opts.fetchImpl
|
|
161
|
+
});
|
|
162
|
+
if (!res.ok) throw apiFailure(url, res);
|
|
163
|
+
if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
|
|
164
|
+
if (res.status !== 200) {
|
|
165
|
+
if (res.status === 400 && rejectedSchemaVersion(res.json)) {
|
|
166
|
+
throw outdatedServerError("The server rejected schemaVersion 2: it predates search v2.", {
|
|
167
|
+
details: res.json
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
throw new CliError(
|
|
171
|
+
"API_UNREACHABLE",
|
|
172
|
+
serverErrorMessage(res.json) ?? `Search failed (${res.status})`,
|
|
173
|
+
{
|
|
174
|
+
fix: "Retry; if it persists the search endpoint may be unavailable.",
|
|
175
|
+
details: res.json
|
|
176
|
+
}
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
const parsed = searchResponseSchema.safeParse(res.json);
|
|
180
|
+
if (!parsed.success) {
|
|
181
|
+
const served = serverSchemaVersion(res.json);
|
|
182
|
+
if (served !== void 0 && served !== 2) {
|
|
183
|
+
throw outdatedServerError(
|
|
184
|
+
`Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,
|
|
185
|
+
{ details: parsed.error.issues }
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
throw new CliError("CONTRACT_MISMATCH", "Search response did not match the expected contract", {
|
|
189
|
+
fix: "Update tenjin-cli; the server contract may have changed.",
|
|
190
|
+
details: parsed.error.issues
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
return truncateResponse(parsed.data);
|
|
194
|
+
}
|
|
195
|
+
function outdatedServerError(message, opts) {
|
|
196
|
+
return new CliError("CONTRACT_MISMATCH", message, {
|
|
197
|
+
fix: "The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.",
|
|
198
|
+
details: opts.details
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
function rejectedSchemaVersion(json) {
|
|
202
|
+
const record = (v) => typeof v === "object" && v !== null ? v : void 0;
|
|
203
|
+
const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;
|
|
204
|
+
return Array.isArray(record(fieldErrors)?.schemaVersion);
|
|
205
|
+
}
|
|
206
|
+
function serverSchemaVersion(json) {
|
|
207
|
+
if (typeof json !== "object" || json === null) return void 0;
|
|
208
|
+
const v = json.schemaVersion;
|
|
209
|
+
return typeof v === "number" ? v : void 0;
|
|
210
|
+
}
|
|
211
|
+
var CAND_BOUNDS = {
|
|
212
|
+
title: 200,
|
|
213
|
+
matchReasons: 3,
|
|
214
|
+
matchReasonChars: 80
|
|
215
|
+
};
|
|
216
|
+
var cap = (s, n) => s.length > n ? s.slice(0, n) : s;
|
|
217
|
+
function truncateResponse(res) {
|
|
218
|
+
const out = { ...res };
|
|
219
|
+
if (res.candidates !== void 0) out.candidates = res.candidates.map(truncateCandidate);
|
|
220
|
+
if (res.browse !== void 0 && res.decision === "MISS") {
|
|
221
|
+
out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({
|
|
222
|
+
resourceId: b.resourceId,
|
|
223
|
+
// Not capped: the schema already refused anything over BROWSE_BOUNDS.url,
|
|
224
|
+
// so this is the url the server sent, verbatim and payable.
|
|
225
|
+
url: b.url,
|
|
226
|
+
title: cap(b.title, BROWSE_BOUNDS.title),
|
|
227
|
+
price: b.price,
|
|
228
|
+
creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) }
|
|
229
|
+
}));
|
|
230
|
+
} else {
|
|
231
|
+
delete out.browse;
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
var BROWSE_MAX = 3;
|
|
236
|
+
function truncateCandidate(c) {
|
|
237
|
+
return {
|
|
238
|
+
...c,
|
|
239
|
+
title: cap(c.title, CAND_BOUNDS.title),
|
|
240
|
+
matchReasons: c.matchReasons.slice(0, CAND_BOUNDS.matchReasons).map((r) => cap(r, CAND_BOUNDS.matchReasonChars))
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
var OUTCOME_STATUSES = [
|
|
244
|
+
"used",
|
|
245
|
+
"partially_used",
|
|
246
|
+
"rejected",
|
|
247
|
+
"regenerated",
|
|
248
|
+
"purchase_declined"
|
|
249
|
+
];
|
|
250
|
+
var OUTCOME_STATUS_VALUES = OUTCOME_STATUSES;
|
|
251
|
+
var CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;
|
|
252
|
+
function buildOutcomeItem(input) {
|
|
253
|
+
if (!OUTCOME_STATUS_VALUES.includes(input.status)) {
|
|
254
|
+
throw new CliError("USAGE", `Invalid outcome status: ${JSON.stringify(input.status)}`, {
|
|
255
|
+
fix: `Use one of: ${OUTCOME_STATUSES.join(", ")}.`
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
if (input.resourceId !== void 0 && !UUID_RE.test(input.resourceId)) {
|
|
259
|
+
throw new CliError("USAGE", `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {
|
|
260
|
+
fix: "Pass the resourceId (a uuid) from a search candidate."
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
if (input.contentHash !== void 0 && !CONTENT_HASH_RE.test(input.contentHash)) {
|
|
264
|
+
throw new CliError("USAGE", `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {
|
|
265
|
+
fix: 'A content hash is "sha256:<64 hex>".'
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
status: input.status,
|
|
270
|
+
...input.resourceId !== void 0 ? { resourceId: input.resourceId } : {},
|
|
271
|
+
...input.contentHash !== void 0 ? { contentHash: input.contentHash } : {}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
var SEARCH_ID_RE = UUID_RE;
|
|
275
|
+
async function postOutcomes(searchId, items, opts) {
|
|
276
|
+
if (!SEARCH_ID_RE.test(searchId)) {
|
|
277
|
+
throw new CliError("USAGE", `Invalid search id: ${JSON.stringify(searchId)}`, {
|
|
278
|
+
fix: "Pass the searchId from a prior search (or use --last)."
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
if (items.length === 0 || items.length > 10) {
|
|
282
|
+
throw new CliError("USAGE", "An outcome report carries 1 to 10 items", {
|
|
283
|
+
fix: "Report between 1 and 10 outcomes per call."
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;
|
|
287
|
+
const res = await httpRequest(url, {
|
|
288
|
+
method: "POST",
|
|
289
|
+
timeoutMs: opts.timeoutMs,
|
|
290
|
+
jsonBody: items.length === 1 ? items[0] : items,
|
|
291
|
+
fetchImpl: opts.fetchImpl
|
|
292
|
+
});
|
|
293
|
+
if (!res.ok) throw apiFailure(url, res);
|
|
294
|
+
if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
|
|
295
|
+
if (res.status !== 202) {
|
|
296
|
+
throw new CliError(
|
|
297
|
+
"API_UNREACHABLE",
|
|
298
|
+
serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,
|
|
299
|
+
{
|
|
300
|
+
fix: "Check the status vocabulary and search id, then retry.",
|
|
301
|
+
details: res.json
|
|
302
|
+
}
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
const accepted = typeof res.json === "object" && res.json !== null && "accepted" in res.json ? Number(res.json.accepted) : items.length;
|
|
306
|
+
return { accepted: Number.isFinite(accepted) ? accepted : items.length };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export {
|
|
310
|
+
MAX_LIMIT,
|
|
311
|
+
buildSearchRequest,
|
|
312
|
+
rateLimitError,
|
|
313
|
+
postSearch,
|
|
314
|
+
buildOutcomeItem,
|
|
315
|
+
postOutcomes
|
|
316
|
+
};
|
|
317
|
+
//# sourceMappingURL=chunk-O6CAUZGY.js.map
|