@coinbase/cdp-cli 2.0.1 → 2.0.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/dist/index.js +197 -137
- package/dist/spec.json +1 -1
- package/dist/version.txt +1 -1
- package/package.json +1 -1
- package/skills/cdp-x402/SKILL.md +78 -10
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var w={live:"https://api.cdp.coinbase.com/platform/v2"};var x={production:"live"};import{readFileSync as Ci}from"node:fs";import{dirname as Bi,join as Ni}from"node:path";import{fileURLToPath as Di}from"node:url";function Xt(t,e){return t.some(r=>r&&typeof r=="object"&&e in r)}function uo(t){return!t||t.length===0?!0:Xt(t,"endUserAuth")?!1:Xt(t,"apiKeyAuth")}function Oe(t){if(t.endpoints[0]?.operation?.tags?.length>0){let e=t.endpoints[0].operation.tags[0],r=e.indexOf(" (");return r>0?e.slice(0,r):e}return""}var po=["get","post","put","patch","delete"],zt={POST:0,GET:1,PUT:2,PATCH:3,DELETE:4};function Zt(t,e){return t.path===e.path?(zt[t.method]??5)-(zt[e.method]??5):t.path<e.path?-1:1}var pt=class{doc;constructor(e){this.doc=e}allEndpoints(){let e=[];for(let[r,n]of Object.entries(this.doc.paths??{}))for(let o of po){let s=n[o];if(!s)continue;let a=this.resolve(s);a?.parameters&&(a.parameters=a.parameters.map(i=>{let c=this.resolve(i);return c?.schema&&(c.schema=this.resolve(c.schema)),c})),uo(a?.security)&&e.push({method:o.toUpperCase(),path:r,summary:a?.summary??"",operation:a})}return e}groups(){let e=new Map;for(let r of this.allEndpoints()){let n=r.path.replace(/^\/v2\//,"").replace(/^\//,"").split("/")[0];(e.get(n)??e.set(n,[]).get(n)).push(r)}return[...e.entries()].map(([r,n])=>(n.sort(Zt),{name:r,endpoints:n})).sort((r,n)=>r.name<n.name?-1:1)}findEndpoints(e){let r=n=>n.replace(/^\/v2\//,"").replace(/^\//,"").split("/")[0];return this.allEndpoints().filter(n=>r(n.path)===e||n.path===e||n.path.startsWith(e)).sort(Zt)}findEndpoint(e,r){let n=this.doc.paths?.[r]?.[e.toLowerCase()];if(!n)return null;let o=this.resolve(n);return o?.parameters&&(o.parameters=o.parameters.map(s=>{let a=this.resolve(s);return a?.schema&&(a.schema=this.resolve(a.schema)),a})),{method:e.toUpperCase(),path:r,summary:o?.summary??"",operation:o}}flattenBodyParams(e){let r=this.resolve(e.requestBody),n=this.resolve(r?.content?.["application/json"]?.schema);if(!n)return[];let o=[];return this.flattenSchema("",n,n.required??[],o),o}getExample(e){return this.resolve(e.requestBody)?.content?.["application/json"]?.example??null}getResponseInfo(e){let r=this.resolve(e.responses?.["200"]??e.responses?.["201"]);if(!r)return null;let n=this.resolve(r.content?.["application/json"]?.schema);if(n?.allOf){let a={properties:{},type:"object"};for(let i of n.allOf){let c=this.resolve(i);c?.properties&&Object.assign(a.properties,c.properties)}n=a}let o=n?.properties?Object.keys(n.properties):[],s=[];if(n?.properties)for(let[a,i]of Object.entries(n.properties)){let c=this.resolve(i),l=c?.type??"object";if(Array.isArray(l)&&(l=l[0]??"string"),l==="array"&&c?.items){let u=this.resolve(c.items);if(u?.properties){let d=Object.keys(u.properties).join(", ");s.push({name:a,type:"array",description:(c.description??"")+` {${d}}`});continue}}s.push({name:a,type:l,description:(c?.description??"").replace(/\n/g," ")})}return{description:r.description??"",fields:o,fieldDetails:s}}getParameters(e){return(e.parameters??[]).map(r=>{let n=this.resolve(r);return n?.schema&&(n.schema=this.resolve(n.schema)),n}).filter(Boolean)}requiresWalletAuth(e){return(e.parameters??[]).some(r=>r?.$ref==="#/components/parameters/XWalletAuth"||this.resolve(r)?.name==="X-Wallet-Auth")}resolve(e){if(!e?.$ref)return e??null;let r=this.doc;for(let n of e.$ref.replace("#/","").split("/"))r=r?.[n];return this.resolve(r)}flattenSchema(e,r,n,o){if(!r)return;if(r.allOf)for(let a of r.allOf){let i=this.resolve(a);i&&this.flattenSchema(e,i,[...n,...i.required??[]],o)}if(!r.properties)return;let s=new Set(n);for(let a of Object.keys(r.properties).sort()){let i=this.resolve(r.properties[a]);if(!i)continue;let c=e?`${e}.${a}`:a;if(i.type==="object"&&i.properties){this.flattenSchema(c,i,i.required??[],o);continue}let l;i.oneOf&&(l=i.oneOf.map(p=>{let f=this.resolve(p);if(!f)return null;if(f.allOf){let y={...f,properties:{},required:[]};for(let m of f.allOf.map(v=>this.resolve(v)).filter(Boolean))m.properties&&Object.assign(y.properties,m.properties),m.required&&y.required.push(...m.required);f=y}if(!f.properties||Object.keys(f.properties).length===0)return null;let g=new Set(f.required??[]),h=f.example??{};return{title:p.title??f.title??"",fields:Object.entries(f.properties).map(([y,m])=>{let v=this.resolve(m),S=v?.type??(v?.allOf?this.resolve(v.allOf[0])?.type??"string":"string");return Array.isArray(S)&&(S=S[0]??"string"),{name:y,type:S,required:g.has(y),description:v?.description??"",example:v?.example??h[y]??null}})}}).filter(Boolean),l.length===0&&(l=void 0));let u=i.type??(l?"object":"string");Array.isArray(u)&&(u=u[0]??"string");let d=i.description??"";if(i.enum?.length&&(d+=(d?" ":"")+`[${i.enum.join(", ")}]`),l){let p=l.map(f=>f.title).filter(Boolean);p.length>0&&(d+=(d?" ":"")+`(one of: ${p.join(", ")})`)}o.push({path:c,type:u,required:s.has(a),description:d,default_:i.default??null,example:i.example??null,oneOf:l})}}},ft=null;function Qt(t){ft=new pt(t)}function B(){if(!ft)throw new Error("spec not initialized");return ft}function mt(t){return(t.match(/\{([^}]+)\}/g)??[]).map(e=>e.slice(1,-1))}function gt(t,e){let r=mt(e);return[...t].sort((n,o)=>{let s=r.indexOf(n.name),a=r.indexOf(o.name);return(s===-1?999:s)-(a===-1?999:a)})}import{createInterface as Ge}from"node:readline/promises";import{readFileSync as Er}from"node:fs";import{readFileSync as go,writeFileSync as ho,mkdirSync as yo}from"node:fs";import{homedir as ir}from"node:os";import{join as Ue}from"node:path";var er="@coinbase/cdp-cli",Ce="https://registry.npmjs.org",tr=typeof w<"u"?w:{live:"https://api.cdp.coinbase.com/platform/v2"},rr=typeof x<"u"?x:{production:"live"},nr="spec.json";import{execFileSync as Be}from"node:child_process";var Ne="/usr/bin/security",De=class{constructor(){try{Be(Ne,["list-keychains"],{stdio:["pipe","pipe","pipe"]})}catch{throw new Error("Keychain not accessible")}}get(e,r){try{return Be(Ne,["find-generic-password","-s",e,"-a",r,"-w"],{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trimEnd()}catch{return null}}set(e,r,n){Be(Ne,["add-generic-password","-U","-s",e,"-a",r,"-w",n],{stdio:["pipe","pipe","pipe"]})}delete(e,r){try{Be(Ne,["delete-generic-password","-s",e,"-a",r],{stdio:["pipe","pipe","pipe"]})}catch{}}};import{execFileSync as qe}from"node:child_process";var Le=class{constructor(){try{qe("which",["secret-tool"],{stdio:["pipe","pipe","pipe"]})}catch{throw new Error("secret-tool not found")}}get(e,r){try{return qe("secret-tool",["lookup","service",e,"account",r],{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trimEnd()}catch{return null}}set(e,r,n){qe("secret-tool",["store","--label",`${e}:${r}`,"service",e,"account",r],{input:n,stdio:["pipe","pipe","pipe"]})}delete(e,r){try{qe("secret-tool",["clear","service",e,"account",r],{stdio:["pipe","pipe","pipe"]})}catch{}}};import{execFileSync as fo}from"node:child_process";function ht(t,e){return`${t}:${e}`}function de(t){return t.replace(/'/g,"''")}var mo=`
|
|
3
3
|
if (-not ([System.Management.Automation.PSTypeName]'Win32.Cred').Type) {
|
|
4
4
|
Add-Type -Namespace Win32 -Name Cred -MemberDefinition '
|
|
5
5
|
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
|
|
@@ -17,7 +17,7 @@ if (-not ([System.Management.Automation.PSTypeName]'Win32.Cred').Type) {
|
|
|
17
17
|
public string TargetAlias; public string UserName;
|
|
18
18
|
}'
|
|
19
19
|
}
|
|
20
|
-
`;function
|
|
20
|
+
`;function yt(t){let e=mo+t,r=Buffer.from(e,"utf16le").toString("base64");return fo("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",r],{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trimEnd()}var Me=class{get(e,r){try{let n=de(ht(e,r));return yt(`
|
|
21
21
|
$ptr = [IntPtr]::Zero
|
|
22
22
|
if ([Win32.Cred]::CredRead('${n}', 1, 0, [ref]$ptr)) {
|
|
23
23
|
$cred = [Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [Type][Win32.Cred+CREDENTIAL])
|
|
@@ -25,7 +25,7 @@ if ([Win32.Cred]::CredRead('${n}', 1, 0, [ref]$ptr)) {
|
|
|
25
25
|
[Runtime.InteropServices.Marshal]::Copy($cred.CredentialBlob, $bytes, 0, $cred.CredentialBlobSize)
|
|
26
26
|
[Win32.Cred]::CredFree($ptr)
|
|
27
27
|
[Text.Encoding]::Unicode.GetString($bytes)
|
|
28
|
-
}`)||null}catch{return null}}set(e,r,n){let o=
|
|
28
|
+
}`)||null}catch{return null}}set(e,r,n){let o=de(ht(e,r)),s=de(r),a=de(n);yt(`
|
|
29
29
|
$bytes = [Text.Encoding]::Unicode.GetBytes('${a}')
|
|
30
30
|
$blob = [Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length)
|
|
31
31
|
[Runtime.InteropServices.Marshal]::Copy($bytes, 0, $blob, $bytes.Length)
|
|
@@ -39,66 +39,69 @@ $cred.Persist = 2
|
|
|
39
39
|
if (-not [Win32.Cred]::CredWrite([ref]$cred, 0)) {
|
|
40
40
|
throw "CredWrite failed: $([Runtime.InteropServices.Marshal]::GetLastWin32Error())"
|
|
41
41
|
}
|
|
42
|
-
[Runtime.InteropServices.Marshal]::FreeHGlobal($blob)`)}delete(e,r){try{
|
|
43
|
-
`),
|
|
44
|
-
`,{mode:384})}function
|
|
45
|
-
`)),!W(n,r))throw new Error(`no URL for environment "${r}". Set url in config or use a built-in env name`);if(n.key_id&&!n.key_secret)throw new Error(`API key secret for "${r}" is stored in the OS keychain but could not be retrieved. This typically occurs in sandboxed environments (e.g. Codex) \u2014 grant the environment access to the OS keychain.`);if(!n.key_id||!n.key_secret)throw new Error(`no API key for "${r}". Run: cdp env ${r} --key-id=...`);return{name:r,env:n}}var
|
|
42
|
+
[Runtime.InteropServices.Marshal]::FreeHGlobal($blob)`)}delete(e,r){try{yt(`[void][Win32.Cred]::CredDelete('${de(ht(e,r))}', 1, 0)`)}catch{}}};var wt="cdp-cli",K,or=!1;function je(){if(K!==void 0)return K;try{process.platform==="darwin"?K=new De:process.platform==="linux"?K=new Le:process.platform==="win32"?K=new Me:K=null}catch{or||(process.stderr.write(`warning: OS keychain not accessible \u2014 secrets stored in keychain will not be available
|
|
43
|
+
`),or=!0),K=null}return K}function Q(t){let e=je();if(!e)return null;try{return e.get(wt,t)}catch{return null}}function pe(t,e){let r=je();if(!r)return!1;try{return r.set(wt,t,e),!0}catch{return!1}}function fe(t){let e=je();if(e)try{e.delete(wt,t)}catch{}}function sr(){return je()!==null}var F=tr,ar=rr;function te(){if(process.env.CDP_CONFIG_DIR)return process.env.CDP_CONFIG_DIR;if(process.platform==="win32"){let t=process.env.APPDATA??Ue(ir(),"AppData","Roaming");return Ue(t,"cdp")}return Ue(ir(),".config","cdp")}function me(){return Ue(te(),"config.json")}function W(t,e){if(t.url)return t.url;if(F[e])return F[e];let r=ar[e];if(r&&F[r])return F[r];let n={...F};for(let[s,a]of Object.entries(ar))F[a]&&(n[s]=F[a]);let o=Object.keys(n).find(s=>e.startsWith(s+"-"));return o?n[o]:""}function ge(t){return Object.values(F).some(e=>t.startsWith(e.replace(/\/platform\/v2$/,"")))}function D(){let t={env:"",environments:{},history:{}},e=me();try{let r=go(e,"utf8"),n=JSON.parse(r);return t.env=n.env??"",t.environments=n.environments??{},t.history=n.history??{},n.settings&&(t.settings=n.settings),t}catch(r){if(r.code!=="ENOENT")throw r instanceof SyntaxError?new Error(`invalid config JSON: ${r.message}`):new Error(`reading config: ${r.message}`)}return t}function q(t){let e=te();yo(e,{recursive:!0,mode:448});let r={env:t.env,environments:t.environments};Object.keys(t.history).length>0&&(r.history=t.history),t.settings&&(r.settings=t.settings),ho(me(),JSON.stringify(r,null,2)+`
|
|
44
|
+
`,{mode:384})}function he(t){return Q(`${t}:wallet`)}function xt(t,e){return pe(`${t}:wallet`,e)}function bt(t){fe(`${t}:wallet`)}function ye(t,e){return e||process.env.CDP_ENV||t.env}function re(t,e){let r=ye(t,e);if(!r)throw new Error("no environment configured. Run: cdp env <name>");let n={...t.environments[r]};if(!n.key_secret){let s=Q(r);s&&(n.key_secret=s)}if(!n.wallet_secret){let s=he(r);s&&(n.wallet_secret=s)}if(process.env.CDP_KEY_ID&&(n.key_id=process.env.CDP_KEY_ID),process.env.CDP_KEY_SECRET&&(n.key_secret=process.env.CDP_KEY_SECRET,delete process.env.CDP_KEY_SECRET),process.env.CDP_WALLET_SECRET&&(n.wallet_secret=process.env.CDP_WALLET_SECRET,delete process.env.CDP_WALLET_SECRET),process.env.CDP_URL&&(n.url=process.env.CDP_URL,ge(n.url)||process.stderr.write(`warning: CDP_URL overrides to non-standard endpoint: ${n.url}
|
|
45
|
+
`)),!W(n,r))throw new Error(`no URL for environment "${r}". Set url in config or use a built-in env name`);if(n.key_id&&!n.key_secret)throw new Error(`API key secret for "${r}" is stored in the OS keychain but could not be retrieved. This typically occurs in sandboxed environments (e.g. Codex) \u2014 grant the environment access to the OS keychain.`);if(!n.key_id||!n.key_secret)throw new Error(`no API key for "${r}". Run: cdp env ${r} --key-id=...`);return{name:r,env:n}}var wo=["CDP_KEY_SECRET","CDP_KEY_ID","CDP_WALLET_SECRET"];function Fe(){let t={...process.env};for(let e of wo)delete t[e];return t}function cr(t){return process.env.CDP_NO_HISTORY?!1:t.settings?.history?.enabled!==!1}function vt(t,e,r){return t.history[e]?.[r]}function Et(t){try{return JSON.parse(t)}catch{return t}}function lr(t,e,r,n){t.history[e]||(t.history[e]={}),t.history[e][r]={last_used:new Date().toISOString(),values:n}}function We(t,e,r){if(e&&r)return t.history[e]?.[r]?(delete t.history[e][r],Object.keys(t.history[e]).length===0&&delete t.history[e],1):0;if(e){let o=Object.keys(t.history[e]??{}).length;return delete t.history[e],o}let n=Object.values(t.history).reduce((o,s)=>o+Object.keys(s).length,0);return t.history={},n}import{createSign as yr,createPrivateKey as Io,createHash as _o,sign as Oo,randomBytes as Co}from"node:crypto";import{readFileSync as xo,writeFileSync as bo,mkdirSync as vo}from"node:fs";import{join as dr}from"node:path";var pr;pr="2.0.2";var V=pr,He=er,Eo=`${Ce}/${encodeURIComponent(He)}`,fr="version-check.json";function ur(t){let e=t.replace(/^v/,"").split("-")[0],[r,n,o]=e.split(".").map(Number);return{major:r??0,minor:n??0,patch:o??0}}function So(t,e){let r=ur(t),n=ur(e);return n.major!==r.major?n.major>r.major:n.minor!==r.minor?n.minor>r.minor:n.patch>r.patch}var ko="https://registry.npmjs.org";function Po(t,e){let r=Ce===ko?"":` --registry ${Ce}`;return`
|
|
46
|
+
Update available: ${t} \u2192 ${e}
|
|
47
|
+
Run: npm i -g ${He}${r}
|
|
48
|
+
`}var $o=1440*60*1e3;function mr(){return te()}function Ro(){try{return JSON.parse(xo(dr(mr(),fr),"utf8"))}catch{return null}}function Ao(t){try{let e=mr();vo(e,{recursive:!0}),bo(dr(e,fr),JSON.stringify(t))}catch{}}async function To(){try{let t=new AbortController,e=setTimeout(()=>t.abort(),3e3),r=await fetch(Eo,{signal:t.signal,headers:{Accept:"application/json"}});return clearTimeout(e),r.ok?(await r.json())?.["dist-tags"]?.latest??null:null}catch{return null}}async function gr(){if(process.env.CI||process.env.CDP_NO_UPDATE_CHECK)return"";let t=Ro();if(t&&Date.now()-t.checkedAt<$o)return"";let e=await To();return e?(Ao({checkedAt:Date.now(),latestVersion:e}),So(V,e)?Po(V,e):""):""}function kt(t){return Buffer.from(t).toString("base64url")}function Ve(t){return kt(Buffer.from(JSON.stringify(t)))}function wr(){return Co(16).toString("hex")}function Bo(t){return t.includes("-----BEGIN EC PRIVATE KEY-----")}function No(t){try{return Buffer.from(t,"base64").length===64}catch{return!1}}function Do(t,e,r,n,o){let s=Math.floor(Date.now()/1e3),a=wr(),i={sub:t,iss:"cdp",nbf:s,iat:s,exp:s+120},c=`${r} ${n}${o}`;if(r&&n&&o&&(i.uris=[c]),Bo(e))return qo(t,e,i,a);if(No(e))return Lo(t,e,i,a);throw new Error("invalid key format - must be either PEM EC key or base64 Ed25519 key")}function xr(t,e,r){let n=`${Ve(t)}.${Ve(e)}`,o=yr("SHA256");o.update(n);let s=o.sign(r);return`${n}.${kt(Mo(s))}`}function qo(t,e,r,n){return xr({alg:"ES256",typ:"JWT",kid:t,nonce:n},r,e)}function Lo(t,e,r,n){let s=`${Ve({alg:"EdDSA",typ:"JWT",kid:t,nonce:n})}.${Ve(r)}`,a=Buffer.from(e,"base64"),i=Io({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),a.subarray(0,32)]),format:"der",type:"pkcs8"}),c=Oo(null,Buffer.from(s),i);return`${s}.${kt(c)}`}function Mo(t){let e=2;if(t[e]!==2)throw new Error("invalid DER signature");e++;let r=t[e];e++;let n=t.subarray(e,e+r);if(e+=r,t[e]!==2)throw new Error("invalid DER signature");e++;let o=t[e];e++;let s=t.subarray(e,e+o);return n=hr(n,32),s=hr(s,32),Buffer.concat([n,s])}function hr(t,e){if(t.length===e)return Buffer.from(t);if(t.length>e)return Buffer.from(t.subarray(t.length-e));let r=Buffer.alloc(e);return r.set(t,e-t.length),r}function jo(t,e,r,n,o){let s=Math.floor(Date.now()/1e3),a=wr(),c={uris:[`${e} ${r}${n}`],iat:s,nbf:s,jti:a};if(o&&o.length>0)try{let u=JSON.parse(new TextDecoder().decode(o));if(typeof u=="object"&&Object.keys(u).length>0){let d=St(u);c.reqHash=_o("sha256").update(JSON.stringify(d)).digest("hex")}}catch{}let l=br(t);return xr({alg:"ES256",typ:"JWT"},c,l)}function br(t){return`-----BEGIN PRIVATE KEY-----
|
|
46
49
|
${Buffer.from(t,"base64").toString("base64").match(/.{1,64}/g)?.join(`
|
|
47
50
|
`)}
|
|
48
|
-
-----END PRIVATE KEY-----`}function
|
|
49
|
-
`);return}let
|
|
50
|
-
`)}return}let n=t[0];if(e.remove){
|
|
51
|
-
`);return}if(e.removeWalletSecret){
|
|
52
|
-
`);return}let o=r.environments[n]??{},s=e.walletSecret??(e.walletSecretFile?
|
|
53
|
-
`);return}if(e.keyFile){let i=
|
|
54
|
-
`))
|
|
55
|
-
`);return}if(e.keyId||e.keySecret||e.url){e.keyId&&(o.key_id=e.keyId),e.keySecret&&(o.key_secret=e.keySecret),e.url&&(o.url=e.url,
|
|
56
|
-
`))
|
|
57
|
-
`);return}if(o.key_id&&(o.key_secret||
|
|
58
|
-
`);return}if(!process.stdout.isTTY)throw new Error(`environment "${n}" needs API keys. Run: cdp env ${n} --key-id=... --key-secret=...`);let a=
|
|
59
|
-
`))}if(!o.wallet_secret&&!
|
|
60
|
-
`)}function
|
|
61
|
-
${n}use --plaintext to store in config file.`)}e.key_secret&&
|
|
51
|
+
-----END PRIVATE KEY-----`}function Pt(t){let e;try{e=Buffer.from(t,"base64")}catch{throw new Error("wallet secret is not valid base64")}if(e.length<100||e.length>300)throw new Error(`wallet secret has unexpected length (${e.length} bytes). Expected a PKCS8 EC key (~138 bytes)`);let r=br(t);try{yr("SHA256").sign(r)}catch{throw new Error("wallet secret is not a valid EC private key")}}function St(t){return Array.isArray(t)?t.map(St):typeof t!="object"||t===null?t:Object.keys(t).sort().reduce((e,r)=>(e[r]=St(t[r]),e),{})}function ne(t,e){e.startsWith("/")||(e="/"+e);let r=new URL(t);return r.pathname=r.pathname.replace(/\/$/,"")+e,r.toString()}async function oe(t){let e=new URL(t.url),n={Authorization:`Bearer ${Do(t.keyId,t.keySecret,t.method,e.host,e.pathname)}`,"Content-Type":"application/json","Correlation-Context":`sdk_version=${encodeURIComponent(V)},sdk_language=typescript,source=${encodeURIComponent(He)}`,...t.headers};t.walletSecret&&(n["X-Wallet-Auth"]=jo(t.walletSecret,t.method,e.host,e.pathname,t.body));let o=await fetch(t.url,{method:t.method,headers:n,body:t.body?Buffer.from(t.body):void 0});return{body:new Uint8Array(await o.arrayBuffer()),status:o.status,headers:o.headers}}async function Sr(t,e){let r=D();if(t.length===0){let i=[...new Set([...Object.keys(r.environments),...Object.keys(F)])].sort();if(i.length===0){process.stderr.write(`No environments configured. Run: cdp env <name>
|
|
52
|
+
`);return}let c=Math.max(14,...i.map(l=>l.length));for(let l of i){let u=r.environments[l]??{},d=W(u,l),p=u.key_id?u.key_id.length>40?u.key_id.slice(0,37)+"...":u.key_id:"(no key)",f=he(l)?" (wallet)":"";process.stdout.write(`${l===r.env?"* ":" "}${l.padEnd(c)} ${(d.length>45?d.slice(0,42)+"...":d).padEnd(45)} ${p}${f}
|
|
53
|
+
`)}return}let n=t[0];if(e.remove){fe(n),bt(n),delete r.environments[n],r.env===n&&(r.env=""),q(r),process.stderr.write(`Removed ${n}.
|
|
54
|
+
`);return}if(e.removeWalletSecret){bt(n),process.stderr.write(`Removed wallet secret for ${n}.
|
|
55
|
+
`);return}let o=r.environments[n]??{},s=e.walletSecret??(e.walletSecretFile?Uo(e.walletSecretFile):void 0);if(s){if(!o.key_id&&!Q(n))throw new Error(`environment "${n}" has no API key. Configure one first: cdp env ${n} --key-file <file>`);Pt(s);let i=!!he(n);xt(n,s),process.stderr.write(`Wallet secret ${i?"updated":"saved"} for ${n}.
|
|
56
|
+
`);return}if(e.keyFile){let i=Fo(e.keyFile);o.key_id=i.keyId,o.key_secret=i.keySecret,e.url&&(o.url=e.url,ge(e.url)||process.stderr.write(`warning: custom URL does not match a known CDP endpoint
|
|
57
|
+
`)),$t(n,o,e.plaintext),r.environments[n]=o,r.env=n,q(r),process.stderr.write(`Loaded key from ${e.keyFile}. Switched to ${n}.
|
|
58
|
+
`);return}if(e.keyId||e.keySecret||e.url){e.keyId&&(o.key_id=e.keyId),e.keySecret&&(o.key_secret=e.keySecret),e.url&&(o.url=e.url,ge(e.url)||process.stderr.write(`warning: custom URL does not match a known CDP endpoint
|
|
59
|
+
`)),$t(n,o,e.plaintext),r.environments[n]=o,r.env=n,q(r),process.stderr.write(`Saved and switched to ${n}.
|
|
60
|
+
`);return}if(o.key_id&&(o.key_secret||Q(n))){r.env=n,q(r),process.stderr.write(`Switched to ${n}.
|
|
61
|
+
`);return}if(!process.stdout.isTTY)throw new Error(`environment "${n}" needs API keys. Run: cdp env ${n} --key-id=... --key-secret=...`);let a=Ge({input:process.stdin,output:process.stderr});try{if(!o.key_id){let i=await a.question("API Key ID: ");if(!i.trim())throw new Error("API Key ID is required");o.key_id=i.trim()}if(!o.key_secret){a.close();let i=await vr("API Key Secret: ");if(!i.trim())throw new Error("API Key Secret is required");o.key_secret=i.trim(),a=Ge({input:process.stdin,output:process.stderr})}if(!o.url&&!W(o,n)){let i=await a.question("URL (optional): ");i.trim()&&(o.url=i.trim(),ge(o.url)||process.stderr.write(`warning: custom URL does not match a known CDP endpoint
|
|
62
|
+
`))}if(!o.wallet_secret&&!he(n)){a.close();let i=await vr("Wallet Secret (optional, press Enter to skip): ");i.trim()&&(Pt(i.trim()),o.wallet_secret=i.trim()),a=Ge({input:process.stdin,output:process.stderr})}}finally{a.close()}$t(n,o),r.environments[n]=o,r.env=n,q(r),process.stderr.write(`Saved. Switched to ${n}.
|
|
63
|
+
`)}function $t(t,e,r){if(!r&&(e.key_secret||e.wallet_secret)){if(!sr()){let n=process.platform==="linux"?"Install libsecret-tools for keyring support, or ":process.platform==="win32"?"Check Windows Credential Manager access, or ":"Check Keychain access (sandboxed environments may not have access), or ";throw new Error(`OS keyring unavailable \u2014 cannot store secrets securely.
|
|
64
|
+
${n}use --plaintext to store in config file.`)}e.key_secret&&pe(t,e.key_secret)&&delete e.key_secret,e.wallet_secret&&xt(t,e.wallet_secret)&&delete e.wallet_secret}}function vr(t){return process.stderr.write(t),process.stdin.isTTY?new Promise(e=>{let r=process.stdin;r.setRawMode(!0),r.resume(),r.setEncoding("utf8");let n="",o=s=>{s===`
|
|
62
65
|
`||s==="\r"||s===""?(r.setRawMode(!1),r.pause(),r.removeListener("data",o),process.stderr.write(`
|
|
63
|
-
`),e(n)):s==="\x7F"||s==="\b"?n=n.slice(0,-1):s===""?process.exit(1):n+=s};r.on("data",o)}):new Promise(e=>{let r=
|
|
64
|
-
Run: cdp env <name> --key-id=... --key-secret=... to configure.`)
|
|
65
|
-
`))}function
|
|
66
|
-
`))}function
|
|
66
|
+
`),e(n)):s==="\x7F"||s==="\b"?n=n.slice(0,-1):s===""?process.exit(1):n+=s};r.on("data",o)}):new Promise(e=>{let r=Ge({input:process.stdin});r.once("line",n=>{r.close(),e(n)})})}function Uo(t){let e;try{e=Er(t,"utf-8").trim()}catch{throw new Error(`cannot read wallet secret file: ${t}`)}if(!e)throw new Error(`wallet secret file is empty: ${t}`);return e}function Fo(t){let e;try{e=Er(t,"utf-8")}catch{throw new Error(`cannot read key file: ${t}`)}let r;try{r=JSON.parse(e)}catch{throw new Error(`key file is not valid JSON: ${t}`)}let n=r.name??r.id,o=r.privateKey??r.secret;if(!n||!o)throw new Error(`key file must contain name/privateKey (or id/secret): ${t}`);return{keyId:n,keySecret:o}}import{readFileSync as Wo,openSync as Ho,readSync as Vo,closeSync as Go}from"node:fs";var Jo={readFile(t){try{return Wo(t)}catch(e){throw new Error(`reading file ${t}: ${e.message}`)}},readStdin(){let t=[],e=Buffer.alloc(65536),r;try{r=Ho("/dev/stdin","r")}catch{throw new Error("reading stdin: cannot open")}try{let n;for(;(n=Vo(r,e))>0;)t.push(Buffer.from(e.subarray(0,n)))}catch{}return Go(r),Buffer.concat(t)}};function Je(t,e=Jo){let r={body:{},query:new URLSearchParams,headers:{},rawBody:null};for(let n of t)if(n==="-")r.rawBody=e.readStdin();else if(n.startsWith("@"))r.rawBody=e.readFile(n.slice(1));else if(Ko(n)){let o=n.indexOf(":");r.headers[n.slice(0,o)]=n.slice(o+1).trim()}else{let o=n.indexOf("=");if(o<=0)throw new Error(`unrecognized argument: ${n} (use key=value, key:=json, key==query, or Header:value)`);if(n[o-1]===":"){let s=n.slice(0,o-1);try{H(r.body,s,JSON.parse(n.slice(o+1)))}catch(a){throw new Error(`invalid JSON in ${s}: ${a.message}`)}}else n[o+1]==="="?r.query.append(n.slice(0,o),n.slice(o+2)):H(r.body,n.slice(0,o),n.slice(o+1))}return r}function Ko(t){let e=t.indexOf(":");return e<=0||t.slice(0,e).includes("=")?!1:t[0]>="A"&&t[0]<="Z"}function kr(t){return Object.keys(t.body).length>0||t.rawBody!==null}function Ke(t){return t.rawBody?t.rawBody:Object.keys(t.body).length===0?null:new TextEncoder().encode(JSON.stringify(t.body))}var Yo=new Set(["__proto__","constructor","prototype"]);function se(t){return!!(t.includes("=")||t.startsWith("@")||t.startsWith("-")||t.indexOf(":")>0&&t[0]>="A"&&t[0]<="Z")}function H(t,e,r){let n=e.split("."),o=t;for(let s=0;s<n.length;s++){let a=n[s];if(Yo.has(a))throw new Error(`invalid field name: ${a}`);if(s===n.length-1){Object.defineProperty(o,a,{value:r,writable:!0,enumerable:!0,configurable:!0});return}(!Object.hasOwn(o,a)||typeof o[a]!="object"||o[a]===null)&&Object.defineProperty(o,a,{value:{},writable:!0,enumerable:!0,configurable:!0}),o=o[a]}}import{execFileSync as Xo}from"node:child_process";function Pr(t,e){try{return Xo("jq",["-r",e],{input:t,encoding:"utf8",maxBuffer:10*1024*1024,env:Fe()}).trimEnd()}catch(r){if(r.code==="ENOENT")throw new Error("jq is not installed. Install it: https://jqlang.github.io/jq/download/");let n=(r.stderr??r.message??"").toString().trim();throw new Error(`jq: ${n}`)}}function $r(t){let e={endpoints:[],children:new Map,param:null};for(let r of t){let n=r.path.replace(/^\/v2\//,"").split("/").filter(Boolean),o=e;for(let s of n)if(s.startsWith("{")&&s.endsWith("}")){let a=s.slice(1,-1);o.param||(o.param={name:a,node:{endpoints:[],children:new Map,param:null}}),o=o.param.node}else o.children.has(s)||o.children.set(s,{endpoints:[],children:new Map,param:null}),o=o.children.get(s);o.endpoints.push(r)}return e}function Rr(t,e){let r=t,n=[];for(let o of e){let s=r.children.get(o);if(s){r=s,n.push(o);continue}if(r.param){r=r.param.node,n.push(o);continue}break}return{node:r,consumed:n}}function Ar(t){return t.children.size>0||t.param!==null}function Ye(t){let e=[...t.endpoints];for(let r of t.children.values())e.push(...Ye(r));return t.param&&e.push(...Ye(t.param.node)),e}function Xe(t,e){let r=new TextDecoder().decode(t),n,o;try{let a=JSON.parse(r);a.errorType&&a.errorMessage?n=`${a.errorType} \u2014 ${a.errorMessage}`:a.message?n=a.message:n=r.length>200?r.slice(0,200)+"...":r,typeof a.correlationId=="string"&&a.correlationId?o=a.correlationId:typeof a.correlation_id=="string"&&a.correlation_id&&(o=a.correlation_id)}catch{n=r.length>200?r.slice(0,200)+"...":r}let s=e?.get("trace-id")??void 0;return{message:n,correlationId:o,traceId:s}}function $(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}function Y(t){return t&&t!=="public"?` [${t}]`:""}function Tr(t,e){return`cdp_${t.replace(/-/g,"_")}_${e.replace(/[-\s]/g,"_")}`}function zo(t,e){let r=e.resolve(t.operation.requestBody),n=e.resolve(r?.content?.["application/json"]?.schema);if(!n?.properties)return"";let o=Object.keys(n.properties).length,s=(n.required??[]).length;return o===0?"":s>0?` (${o} fields, ${s} required)`:` (${o} fields)`}function Zo(t,e,r,n){let o=e.resolve(t.operation.requestBody),s=e.resolve(o?.content?.["application/json"]?.schema);if(!s?.properties)return;let a=new Set(s.required??[]);for(let[i,c]of Object.entries(s.properties)){let l=e.resolve(c),u={type:l.type??"string"};if(l.description){let d=l.description.replace(/\n/g," ");u.description=d.length>80?d.slice(0,77)+"...":d}l.enum&&(u.enum=l.enum),l.example!=null&&(u.example=l.example),r[i]=u,a.has(i)&&n.push(i)}}function Ir(t,e){let r=[{name:"cdp_env",description:"Show the active CDP environment and configured environments.",inputSchema:{type:"object",properties:{}}},{name:"cdp_template",description:"Get a full request body example for a resource action, ready to copy and modify.",inputSchema:{type:"object",properties:{resource:{type:"string",description:'Resource name (e.g. "transfers")'},action:{type:"string",description:'Action name (e.g. "create")'}},required:["resource","action"]}},{name:"cdp_help",description:"Get detailed help for a resource action: field descriptions, response schema, and usage.",inputSchema:{type:"object",properties:{resource:{type:"string",description:"Resource name"},action:{type:"string",description:"Action name"}},required:["resource","action"]}},{name:"cdp_set_env",description:"Switch the active CDP environment. Only switches between already-configured environments.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Environment name to switch to (e.g., "live", "production")'}},required:["name"]}}];for(let n of e)for(let o of n.actions){let s={},a=[];for(let i of o.pathParams)s[i]={type:"string",description:`Path parameter: ${i}`},a.push(i);Zo(o,t,s,a);for(let i of t.getParameters(o.operation))i?.in==="query"&&(s[i.name]={type:i.schema?.type??"string",description:i.description??i.schema?.description??i.name});r.push({name:Tr(n.name,o.name),description:`${o.method} ${o.path}${o.summary?" \u2014 "+o.summary:""}${zo(o,t)}${Y(o.audience)}`,inputSchema:{type:"object",properties:s,required:a.length>0?a:void 0}})}return r}function _r(t,e,r){let n=t.path.replace(/^\/v2/,"");for(let c of t.pathParams){if(!e[c])return $(`Missing required parameter: ${c}`,!0);n=n.replace(`{${c}}`,e[c])}let o=new Set(t.pathParams),s=new Set,a=new URLSearchParams;for(let c of r.getParameters(t.operation))c?.in==="query"&&(s.add(c.name),e[c.name]!=null&&a.set(c.name,String(e[c.name])));let i=null;if(e.body&&typeof e.body=="object")i=new TextEncoder().encode(JSON.stringify(e.body));else{let c={};for(let[l,u]of Object.entries(e))!o.has(l)&&!s.has(l)&&(c[l]=u);Object.keys(c).length>0&&(i=new TextEncoder().encode(JSON.stringify(c)))}return{method:t.method,urlPath:n,queryParams:a,body:i}}function Or(t){return"urlPath"in t}function Cr(t,e,r){if(t>=400){let o=Xe(e,r),s=`HTTP ${t}: ${o.message}`,a=[o.traceId?`trace ${o.traceId}`:"",o.correlationId?`correlation ${o.correlationId}`:""].filter(Boolean).join(", ");return a&&(s+=` [${a}]`),$(s,!0)}let n=new TextDecoder().decode(e);try{return $(JSON.stringify(JSON.parse(n),null,2))}catch{return $(n)}}function Br(t,e){let r=t.startsWith("cdp_")?t.slice(4):t;for(let n of e){let o=n.name.replace(/-/g,"_");for(let s of n.actions)if(`${o}_${s.name.replace(/[-\s]/g,"_")}`===r)return{resource:n,action:s}}return null}function Rt(t){let e=ye(t,""),r=Object.keys(t.environments??{}),n=[`Active: ${e||"(none)"}`,`Configured: ${r.length>0?r.join(", "):"(none)"}`];return e||n.push(`
|
|
67
|
+
Run: cdp env <name> --key-id=... --key-secret=... to configure.`),$(n.join(`
|
|
68
|
+
`))}function Nr(t,e){if(!e)return $("Environment name is required.",!0);let r=Object.keys(t.environments??{});return r.length===0?$("No environments configured. Run: cdp env <name> --key-id=... --key-secret=... to configure.",!0):t.environments[e]?{cfg:{...t,env:e}}:$(`Unknown environment: "${e}". Available environments: ${r.join(", ")}`,!0)}function Dr(t){return Rt(t)}function qr(t,e,r,n){if(!t||!e)return $("resource and action are required",!0);let o=r.find(p=>p.name===t);if(!o)return $(`Unknown resource: ${t}. Available: ${r.map(p=>p.name).join(", ")}`,!0);let s=o.actions.find(p=>p.name===e);if(!s)return $(`Unknown action: ${e}. Available for ${t}: ${o.actions.map(p=>p.name).join(", ")}`,!0);let a=[];a.push(`${s.summary||s.name}${Y(s.audience)}`),a.push(`${s.method} ${s.path}`);let i=Tr(o.name,s.name),c=s.pathParams.map(p=>`${p}="..."`).join(", ");a.push("",`Usage: ${i}(${c})`);let l=n.flattenBodyParams(s.operation);if(l.length>0){a.push("","Fields:");for(let p of l){let f=p.required?" (required)":"",g=p.description?` \u2014 ${p.description}`:"";if(p.oneOf){a.push(` ${p.path}: one of:`);for(let h of p.oneOf)a.push(` ${h.title||"variant"}: { ${h.fields.map(y=>y.name).join(", ")} }`)}else a.push(` ${p.path} (${p.type})${f}${g}`)}}let u=n.getParameters(s.operation).filter(p=>p?.in==="query");if(u.length>0){a.push("","Query parameters:");for(let p of u){let f=p.description||p.schema?.description?` \u2014 ${p.description||p.schema?.description}`:"";a.push(` ${p.name} (${p.schema?.type??"string"})${f}`)}}let d=n.getResponseInfo(s.operation);if(d&&d.fieldDetails.length>0){a.push("","Response fields:");for(let p of d.fieldDetails)a.push(` ${p.name} (${p.type})${p.description?" \u2014 "+p.description:""}`)}return $(a.join(`
|
|
69
|
+
`))}function ze(t,e){let r={};for(let n of e.flattenBodyParams(t.operation))if(n.oneOf&&n.oneOf.length>0){let o={};for(let s of n.oneOf[0].fields)o[s.name]=At(s);H(r,n.path,o)}else H(r,n.path,n.example??n.default_??(n.required?`<required:${n.type}>`:`<${n.type}>`));return r}function At(t){if(t.example!=null)return t.example;switch(t.type){case"integer":case"number":return 0;case"boolean":return!1;case"array":return[];case"object":return{};default:return""}}function Lr(t,e,r,n){if(!t||!e)return $("resource and action are required",!0);let o=r.find(l=>l.name===t);if(!o)return $(`Unknown resource: ${t}. Available: ${r.map(l=>l.name).join(", ")}`,!0);let s=o.actions.find(l=>l.name===e);if(!s)return $(`Unknown action: ${e}. Available for ${t}: ${o.actions.map(l=>l.name).join(", ")}`,!0);let a=n.flattenBodyParams(s.operation);if(a.length===0)return $("This action has no request body.");let i=ze(s,n),c=[];for(let l of a){let u=l.required?" (required)":"",d=l.description?` \u2014 ${l.description}`:"";if(l.oneOf){c.push(`${l.path}: one of:`);for(let p of l.oneOf)c.push(` ${p.title||"variant"}: { ${p.fields.map(f=>f.name).join(", ")} }`)}else c.push(`${l.path} (${l.type})${u}${d}`)}return $(`Template:
|
|
67
70
|
${JSON.stringify(i,null,2)}
|
|
68
71
|
|
|
69
72
|
Fields:
|
|
70
|
-
${
|
|
71
|
-
`)}`)}function
|
|
72
|
-
`),i="",
|
|
73
|
-
`)}function
|
|
73
|
+
${c.join(`
|
|
74
|
+
`)}`)}function Qo(t,e){return t.FORCE_HYPERLINK==="0"?!1:t.FORCE_HYPERLINK?!0:!e||t.CI?!1:!!(/ghostty|iterm|wezterm|hyper/i.test(t.TERM_PROGRAM||"")||t.WT_SESSION||parseInt(t.VTE_VERSION||"",10)>=5e3)}var Mr=Qo(process.env,!!process.stdout.isTTY);function Tt(t){return t.replace(/\x1b\]8;;[^\x07]*\x07/g,"").replace(/\x1b\[[0-9;]*m/g,"").length}function X(t,e,r,n){let o=n??e.length,s=Math.max(20,(process.stdout.columns||80)-o),a=r.split(" "),i="",c=!0;for(let l of a){let u=Tt(l),d=Tt(i),p=l.includes("\x1B]8;;");(d+u+1>s||p&&d>0&&d+u+1>s*.6)&&i.length>0&&(t.write((c?e:" ".repeat(o))+i.trimEnd()+`
|
|
75
|
+
`),i="",c=!1),i+=(i?" ":"")+l}i&&t.write((c?e:" ".repeat(o))+i.trimEnd()+`
|
|
76
|
+
`)}function es(t,e,r){return r?`\x1B]8;;${e}\x07\x1B[4m${t}\x1B[24m\x1B]8;;\x07`:`${t} (${e})`}function Ze(t,e=Mr){return t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,o)=>es(n,o,e))}function we(t){return t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^#{1,6}\s+/gm,"")}function Qe(t,e){let r=e??process.stdout.columns??100;return t.replace(/\r\n/g,`
|
|
74
77
|
`).trim().split(`
|
|
75
|
-
`).flatMap(n=>{n=
|
|
78
|
+
`).flatMap(n=>{n=we(n).replace(/^\s*\*\s+/," - ").replace(/^\s*(\d+)\.\s+/," $1. ");let o=[];for(;n.length>r;){let s=n.lastIndexOf(" ",r);s<=0&&(s=r),o.push(n.slice(0,s)),n=n.slice(s+1)}return o.push(n),o}).join(`
|
|
76
79
|
`)+`
|
|
77
|
-
`}function
|
|
78
|
-
`)}}function
|
|
79
|
-
`);let n=t[r];process.stdout.write(`${n.method.padEnd(5)} ${n.path.replace(/^\/v2/,"").padEnd(45)} ${n.summary}${
|
|
80
|
-
`),
|
|
81
|
-
`)}}}function
|
|
82
|
-
`),
|
|
80
|
+
`}function jr(t){let e=B();if(t.length===0)return ts(e);if(t.length===1)return rs(e,t[0]);if(t.length===2)return ns(e,t[0],t[1]);throw new Error("usage: cdp api [group | METHOD /path | /path]")}function ts(t){for(let e of t.groups()){let r=Oe(e);process.stdout.write(`${e.name.padEnd(24)} ${String(e.endpoints.length).padStart(2)} endpoints ${r}
|
|
81
|
+
`)}}function rs(t,e){let r=t.findEndpoints(e.startsWith("/")?"/v2"+e:e);if(r.length===0)throw new Error(e.startsWith("/")?`no endpoints found for path: ${e}`:`no API group named "${e}". Run: cdp api`);os(r,t)}function ns(t,e,r){let n=t.findEndpoint(e.toUpperCase(),r.startsWith("/v2")?r:"/v2"+r);if(!n)throw new Error(`no endpoint: ${e} ${r}`);It(n,t)}function os(t,e){for(let r=0;r<t.length;r++){r>0&&process.stdout.write(`
|
|
82
|
+
`);let n=t[r];process.stdout.write(`${n.method.padEnd(5)} ${n.path.replace(/^\/v2/,"").padEnd(45)} ${n.summary}${Y(n.operation?.["x-audience"]??"")}
|
|
83
|
+
`),ss(n,e)}}function ie(t,e,r=!1){if(t.length===0)return;let n=Math.max(...t.map(i=>i.name.length))+1,o=Math.max(...t.map(i=>i.type.length))+1,s=Math.max(...t.map(i=>i.req.length)),a=" ".repeat(e);for(let i of t){let c=`${a}${i.name.padEnd(n)}${i.type.padEnd(o)}${s>0?i.req.padEnd(s)+" ":""}`,l=Ze(we(i.desc.replace(/\n/g," ").trim()));if(r)X(process.stdout,c,l);else{let u=Math.max((process.stdout.columns||100)-c.length,20);process.stdout.write(`${c}${l.length>u?l.slice(0,u-3)+"...":l}
|
|
84
|
+
`)}}}function ss(t,e){let r=e.flattenBodyParams(t.operation);r.length>0&&(process.stdout.write(` body:
|
|
85
|
+
`),ie(r.map(i=>({name:i.path,type:i.type,req:i.required?"required":"",desc:i.description})),4));let n=e.getParameters(t.operation),o=t.path??"",s=gt(n.filter(i=>i?.in==="path"),o).map(i=>i.name),a=n.filter(i=>i?.in==="query").map(i=>i.name);s.length>0&&process.stdout.write(` path: ${s.join(", ")}
|
|
83
86
|
`),a.length>0&&process.stdout.write(` query: ${a.join(", ")}
|
|
84
|
-
`)}function
|
|
87
|
+
`)}function It(t,e){let r=process.stdout,n=t.path.replace(/^\/v2/,"");r.write(`${t.method} \u2014 ${t.summary||n}${Y(t.operation?.["x-audience"]??"")}
|
|
85
88
|
`),t.operation.description&&r.write(`
|
|
86
|
-
`+
|
|
89
|
+
`+Qe(t.operation.description)),r.write(`
|
|
87
90
|
Usage:
|
|
88
91
|
cdp api -X ${t.method} ${n}
|
|
89
|
-
`);let o=e.getParameters(t.operation),s={};for(let u of o)u&&(s[u.in]??=[]).push({name:u.name,type:u.schema?.type??"string",req:u.required?"required":"",desc:u.description??u.schema?.description??""});s.path?.length&&(s.path=
|
|
92
|
+
`);let o=e.getParameters(t.operation),s={};for(let u of o)u&&(s[u.in]??=[]).push({name:u.name,type:u.schema?.type??"string",req:u.required?"required":"",desc:u.description??u.schema?.description??""});s.path?.length&&(s.path=gt(s.path,t.path),r.write(`
|
|
90
93
|
Path parameters:
|
|
91
|
-
`),
|
|
94
|
+
`),ie(s.path,2,!0)),s.query?.length&&(r.write(`
|
|
92
95
|
Query parameters:
|
|
93
|
-
`),
|
|
96
|
+
`),ie(s.query,2,!0));let a=e.flattenBodyParams(t.operation);a.length>0&&(r.write(`
|
|
94
97
|
Request body:
|
|
95
|
-
`),
|
|
98
|
+
`),ie(a.map(u=>{let d=u.description;if(u.default_!==null){let p=`default: ${u.default_}`;d=d?`${d} (${p})`:p}return{name:u.path,type:u.type,req:u.required?"required":"",desc:d}}),2,!0));let i=e.getResponseInfo(t.operation);i&&(r.write(`
|
|
96
99
|
Response 200: ${i.description}
|
|
97
|
-
`),i.fieldDetails.length>0&&
|
|
100
|
+
`),i.fieldDetails.length>0&&ie(i.fieldDetails.map(u=>({name:u.name,type:u.type,req:"",desc:u.description})),2,!0));let c=new Set,l=[];for(let u of a)if(u.oneOf)for(let d of u.oneOf)c.has(d.title)||(c.add(d.title),l.push(d));if(l.length>0){process.stdout.write(`
|
|
98
101
|
Types:
|
|
99
|
-
`);for(let u=0;u<
|
|
100
|
-
`),process.stdout.write(` ${
|
|
101
|
-
`),
|
|
102
|
+
`);for(let u=0;u<l.length;u++)u>0&&process.stdout.write(`
|
|
103
|
+
`),process.stdout.write(` ${l[u].title}
|
|
104
|
+
`),ie(l[u].fields.map(d=>({name:d.name,type:d.type,req:d.required?"required":"",desc:d.description})),4,!0)}}function et(t,e){try{let r=JSON.parse(new TextDecoder().decode(e))?.nextPageToken;if(!r||typeof r!="string")return null;let n=new URL(t);return n.searchParams.set("pageToken",r),n.toString()}catch{return null}}function L(t,e){let r={},n=[],o=!1,s=new Map;for(let[a,i,c]of e)s.set("--"+a,[a,c]),i&&s.set("-"+i,[a,c]);for(let a=0;a<t.length;a++){let i=t[a];if(i==="-h"||i==="--help"){o=!0;continue}let c=i.indexOf("=");if(c>0&&i.startsWith("--")){let u=s.get(i.slice(0,c));if(u){r[u[0]]=i.slice(c+1);continue}}let l=s.get(i);if(l){r[l[0]]=l[1]?t[++a]??"":!0;continue}if(i.length>2&&i[0]==="-"&&i[1]!=="-"){let u=s.get(i.slice(0,2));if(u?.[1]){r[u[0]]=i.slice(2);continue}}n.push(i)}return{flags:r,args:n,help:o}}var _t=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];function is(t){return t.length>=2&&_t.includes(t[0].toUpperCase())&&t[1].startsWith("/")?{method:t[0],pathIdx:1}:{method:void 0,pathIdx:0}}function as(t){if(t.startsWith("-"))return"";if(!t.startsWith("/"))throw new Error(`paths must start with /: cdp api /${t}`);let e=t.slice(1);return e.startsWith("v2/")&&(e=e.slice(3)),e}function cs(t){let e=t.filter(r=>!se(r)&&!_t.includes(r.toUpperCase()));if(e.length>1)throw new Error(`paths must use / separators, not spaces: cdp api /${e.map(r=>r.replace(/^\//,"")).join("/")}`)}function ls(t,e){let r=t.toLowerCase();return r==="authorization"||r.includes("key")||r.includes("token")||r.includes("secret")?"***":e}async function Ur(t,e){if(t.length===0){jr([]);return}let r=t.includes("--help")||t.includes("-h"),n=t.filter(P=>P!=="--help"&&P!=="-h"),o=n[0]??"";if(r&&!o){process.stderr.write(`Raw API access and endpoint browser
|
|
102
105
|
|
|
103
106
|
Usage:
|
|
104
107
|
cdp api List all API endpoints
|
|
@@ -121,35 +124,32 @@ Flags:
|
|
|
121
124
|
-i, --include Include response headers
|
|
122
125
|
-v, --verbose Show full request and response
|
|
123
126
|
--paginate Auto-paginate using nextPageToken
|
|
124
|
-
`);return}let s=B(),a=s.groups().flatMap(P=>P.endpoints),i
|
|
125
|
-
`),
|
|
127
|
+
`);return}let s=B(),a=s.groups().flatMap(P=>P.endpoints),i=$r(a);cs(n);let c=as(o);if(c){let P=c.split("/").filter(Boolean),{node:A,consumed:E}=Rr(i,P),_=n.find(C=>_t.includes(C.toUpperCase())),dt=E.length===P.length,oo=n.some(C=>C==="-X"||C==="--method"||C.startsWith("--method=")),so=n.some((C,ue)=>ue>0&&se(C)&&C!=="-X"&&C!=="--method"&&!C.startsWith("--method=")),io=Ar(A);if(dt&&(r||A.endpoints.length===0||io&&!oo&&!so)){let C=_?A.endpoints.filter(M=>M.method===_.toUpperCase()):A.endpoints;if(C.length>0&&r)for(let M=0;M<C.length;M++)M>0&&process.stdout.write(`
|
|
128
|
+
`),It(C[M],s);let ue=Ye(A).filter(M=>!C.includes(M));if(ue.length>0){C.length>0&&process.stderr.write(`
|
|
126
129
|
Sub-paths:
|
|
127
|
-
`);for(let
|
|
128
|
-
`)}}if(
|
|
129
|
-
> Host: ${
|
|
130
|
-
`);for(let[_,
|
|
130
|
+
`);for(let M of ue){let ao=M.path.replace(/^\/v2/,"");process.stderr.write(` ${M.method.padEnd(6)} ${ao}
|
|
131
|
+
`)}}if(C.length>0||ue.length>0)return}}let l=L(t,[["method","X",!0],["jq",null,!0],["include","i",!1],["verbose","v",!1],["paginate",null,!1]]),u=l.args,d={method:l.flags.method,jq:l.flags.jq,include:!!l.flags.include,verbose:!!l.flags.verbose,paginate:!!l.flags.paginate,envFlag:e.envFlag};if(u.length===0)throw new Error("usage: cdp api <path> [fields...]");let{method:p,pathIdx:f}=is(u);p&&(d.method=p);let g=D(),{name:h,env:y}=re(g,d.envFlag),m=W(y,h),v=Je(u.slice(f+1)),S=(d.method??"").toUpperCase()||(kr(v)?"POST":"GET"),b=ne(m,u[f]),I=v.query.toString();I&&(b+=(b.includes("?")?"&":"?")+I);let N=Ke(v),R={method:S,body:N,headers:v.headers,keyId:y.key_id,keySecret:y.key_secret,walletSecret:y.wallet_secret},O=b;do{if(d.verbose){let E=new URL(O);process.stderr.write(`> ${S} ${E.pathname}${E.search}
|
|
132
|
+
> Host: ${E.host}
|
|
133
|
+
`);for(let[_,dt]of Object.entries(v.headers))process.stderr.write(`> ${_}: ${ls(_,dt)}
|
|
131
134
|
`);process.stderr.write(`>
|
|
132
|
-
`)}let P=await
|
|
133
|
-
`),P.headers.forEach((
|
|
135
|
+
`)}let P=await oe({...R,url:O});if(d.verbose&&(process.stderr.write(`< HTTP ${P.status}
|
|
136
|
+
`),P.headers.forEach((E,_)=>process.stderr.write(`< ${_}: ${E}
|
|
134
137
|
`)),process.stderr.write(`<
|
|
135
138
|
`)),d.include&&(process.stdout.write(`HTTP ${P.status}
|
|
136
|
-
`),P.headers.forEach((
|
|
139
|
+
`),P.headers.forEach((E,_)=>process.stdout.write(`${_}: ${E}
|
|
137
140
|
`)),process.stdout.write(`
|
|
138
|
-
`)),
|
|
141
|
+
`)),Ot(P,d.jq),!d.paginate)break;let A=et(O,P.body);if(!A)break;O=A}while(!0)}function Ot(t,e){let r=t.status>=400;if(e)try{process.stdout.write(Pr(t.body,e)+`
|
|
139
142
|
`)}catch(n){process.stdout.write(new TextDecoder().decode(t.body)+`
|
|
140
143
|
`),process.stderr.write(`jq error: ${n.message}
|
|
141
144
|
`)}else if(!(r&&process.stdout.isTTY)){let n=new TextDecoder().decode(t.body);if(process.stdout.isTTY)try{process.stdout.write(JSON.stringify(JSON.parse(n),null,2)+`
|
|
142
145
|
`)}catch{process.stdout.write(n+`
|
|
143
146
|
`)}else process.stdout.write(n+`
|
|
144
|
-
`)}if(r){let n=
|
|
145
|
-
|
|
146
|
-
Run: npm i -g ${kr}${r}
|
|
147
|
-
`}var qo=1440*60*1e3;function Rr(){return se()}function Lo(){try{return JSON.parse(To(Sr(Rr(),Pr),"utf8"))}catch{return null}}function jo(t){try{let e=Rr();Co(e,{recursive:!0}),_o(Sr(e,Pr),JSON.stringify(t))}catch{}}async function Mo(){try{let t=new AbortController,e=setTimeout(()=>t.abort(),3e3),r=await fetch(Oo,{signal:t.signal,headers:{Accept:"application/json"}});return clearTimeout(e),r.ok?(await r.json())?.["dist-tags"]?.latest??null:null}catch{return null}}async function Ar(){if(process.env.CI||process.env.CDP_NO_UPDATE_CHECK)return"";let t=Lo();if(t&&Date.now()-t.checkedAt<qo)return"";let e=await Mo();return e?(jo({checkedAt:Date.now(),latestVersion:e}),Bo(ne,e)?Do(ne,e):""):""}function Tr(t){process.stdout.write(JSON.stringify({jsonrpc:"2.0",...t})+`
|
|
148
|
-
`)}function ve(t,e){Tr({id:t,result:e})}function Ee(t,e,r){Tr({id:t,error:{code:e,message:r}})}async function Fo(t,e){let r=B(),n=de(r);if(t==="cdp_env")return wt(D());if(t==="cdp_set_env"){let o=D(),s=fr(o,e.name);return"isError"in s?s:(q(s.cfg),mr(s.cfg))}return t==="cdp_help"?gr(e.resource,e.action,n,r):t==="cdp_template"?hr(e.resource,e.action,n,r):Wo(t,e)}async function Wo(t,e){let r=B(),n=de(r),o=pr(t,n);if(!o)return T(`Unknown tool: ${t}`,!0);let{action:s}=o,a=lr(s,e,r);if(!ur(a))return a;let i=D(),l;try{l=ie(i,"")}catch(f){return T(`Environment error: ${f.message}
|
|
147
|
+
`)}if(r){let n=Xe(t.body,t.headers),o=[n.traceId?`trace ${n.traceId}`:"",n.correlationId?`correlation ${n.correlationId}`:""].filter(Boolean).join(", ");throw new Error(`${n.message} (HTTP ${t.status})${o?` [${o}]`:""}`)}}import{createInterface as ps}from"node:readline";function ae(t){let e=t.groups(),r=[];for(let n of e){let o=[];for(let a of n.endpoints){let i=ds(n.name,a);i&&o.push(i)}let s=us(o);s.sort((a,i)=>{let c=Fr(a.name),l=Fr(i.name);if(c!==l)return c<l?-1:1;let u=Wr(a.name),d=Wr(i.name);return u!==d?u-d:a.name<i.name?-1:a.name>i.name?1:0}),s.length>0&&r.push({name:n.name,actions:s})}return r.sort((n,o)=>n.name<o.name?-1:1),r}function us(t){let e=new Map;for(let r of t)e.set(r.name,(e.get(r.name)??0)+1);return t.map(r=>{if((e.get(r.name)??0)>1){let n=r.path.endsWith("}");return{...r,name:`${r.name} ${tt(r.method,n)}`}}return r})}function tt(t,e){if(t==="GET")return e?"get":"list";switch(t){case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return t.toLowerCase()}}function ds(t,e){let r=e.path.replace(`/v2/${t}`,"").replace(/^\//,""),n=r?r.split("/"):[],o=n.filter(l=>l[0]!=="{"),s=n.length>0&&n[n.length-1][0]==="{",a=mt(e.path),i;n.length===0?i=tt(e.method,!1):s&&o.length===0?i=tt(e.method,!0):s&&o.length<=1?i=o[0]+" "+tt(e.method,!0):i=o.join(" ");let c=e.operation?.["x-audience"]??"";return{name:i,method:e.method,path:e.path,summary:e.summary,audience:c,operation:e.operation,pathParams:a}}function Fr(t){let e=t.split(" ");return e.length>1?e.slice(0,-1).join(" "):""}function Wr(t){switch(t.split(" ").pop()){case"create":return 0;case"list":return 1;case"get":return 2;case"update":return 3;case"delete":return 4;default:return 5}}function Vr(t){process.stdout.write(JSON.stringify({jsonrpc:"2.0",...t})+`
|
|
148
|
+
`)}function xe(t,e){Vr({id:t,result:e})}function be(t,e,r){Vr({id:t,error:{code:e,message:r}})}async function fs(t,e){let r=B(),n=ae(r);if(t==="cdp_env")return Rt(D());if(t==="cdp_set_env"){let o=D(),s=Nr(o,e.name);return"isError"in s?s:(q(s.cfg),Dr(s.cfg))}return t==="cdp_help"?qr(e.resource,e.action,n,r):t==="cdp_template"?Lr(e.resource,e.action,n,r):ms(t,e)}async function ms(t,e){let r=B(),n=ae(r),o=Br(t,n);if(!o)return $(`Unknown tool: ${t}`,!0);let{action:s}=o,a=_r(s,e,r);if(!Or(a))return a;let i=D(),c;try{c=re(i,"")}catch(f){return $(`Environment error: ${f.message}
|
|
149
149
|
|
|
150
|
-
Run: cdp env <name> --key-id=... --key-secret=...`,!0)}let{name:
|
|
151
|
-
`),r.id!=null&&
|
|
152
|
-
`)}import{readFileSync as
|
|
150
|
+
Run: cdp env <name> --key-id=... --key-secret=...`,!0)}let{name:l,env:u}=c,d=ne(W(u,l),a.urlPath),p=a.queryParams.toString();p&&(d+=(d.includes("?")?"&":"?")+p);try{let f=await oe({method:a.method,url:d,body:a.body,keyId:u.key_id,keySecret:u.key_secret,walletSecret:u.wallet_secret});return Cr(f.status,f.body,f.headers)}catch(f){return $(`Request failed: ${f.message}`,!0)}}var gs={name:"cdp",version:V},hs={tools:{}},Ct=null;function Hr(){return Ct||(Ct=Ir(B(),ae(B()))),Ct}async function ys(t){let{id:e,method:r,params:n}=t;switch(r){case"initialize":xe(e,{protocolVersion:"2024-11-05",serverInfo:gs,capabilities:hs});break;case"notifications/initialized":break;case"tools/list":xe(e,{tools:Hr()});break;case"tools/call":{let{name:o,arguments:s}=n??{};if(!o){be(e,-32602,"Missing tool name");return}if(!Hr().find(i=>i.name===o)){be(e,-32602,`Unknown tool: ${o}`);return}try{let i=await fs(o,s??{});xe(e,i)}catch(i){xe(e,$(`Internal error: ${i.message}`,!0))}break}case"ping":xe(e,{});break;default:e!=null&&be(e,-32601,`Method not found: ${r}`);break}}function Gr(){let t=ps({input:process.stdin,terminal:!1});t.on("line",e=>{if(e.trim())try{let r=JSON.parse(e);ys(r).catch(n=>{process.stderr.write(`MCP error: ${n.message}
|
|
151
|
+
`),r.id!=null&&be(r.id,-32603,n.message)})}catch{be(null,-32700,"Parse error")}}),t.on("close",()=>process.exit(0)),process.stderr.write(`CDP MCP server v${V} ready
|
|
152
|
+
`)}import{readFileSync as Ws}from"node:fs";var Bt={base:{chainId:8453,rpc:"https://mainnet.base.org"},"base-sepolia":{chainId:84532,rpc:"https://sepolia.base.org"},ethereum:{chainId:1,rpc:"https://eth.llamarpc.com"},"ethereum-sepolia":{chainId:11155111,rpc:"https://rpc.sepolia.org"},"ethereum-hoodi":{chainId:560048,rpc:"https://rpc.hoodi.ethpandaops.io"},arbitrum:{chainId:42161,rpc:"https://arb1.arbitrum.io/rpc"},optimism:{chainId:10,rpc:"https://mainnet.optimism.io"},polygon:{chainId:137,rpc:"https://polygon-rpc.com"},avalanche:{chainId:43114,rpc:"https://api.avax.network/ext/bc/C/rpc"}},rt={solana:{cluster:"mainnet-beta",rpc:"https://api.mainnet-beta.solana.com",genesisHash:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"},"solana-devnet":{cluster:"devnet",rpc:"https://api.devnet.solana.com",genesisHash:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1"},"solana-testnet":{cluster:"testnet",rpc:"https://api.testnet.solana.com",genesisHash:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"}};function Jr(t,e){let r=t.toLowerCase(),n=Bt[r];if(n)return{chain:"evm",chainId:n.chainId,rpc:e||n.rpc,name:r};let o=rt[r];if(o)return{chain:"solana",cluster:o.cluster,rpc:e||o.rpc,name:r};throw new Error(`unknown network: ${t}. Supported: ${[...Object.keys(Bt),...Object.keys(rt)].join(", ")}`)}function ve(t){return t.startsWith("eip155:")}function Ee(t){return t.startsWith("solana:")}function nt(t){if(!ve(t))throw new Error(`not an EVM network: ${t}`);let e=parseInt(t.split(":")[1],10);if(isNaN(e))throw new Error(`invalid chain ID in network: ${t}`);return e}function Nt(t){if(t.includes(":"))return t;let e=Bt[t];if(e)return`eip155:${e.chainId}`;let r=rt[t];return r?`solana:${r.genesisHash}`:t}function Kr(t){for(let[e,r]of Object.entries(rt))if(t===`solana:${r.genesisHash}`)return{name:e,rpc:r.rpc}}function Dt(t){if(Buffer.isBuffer(t))return t.length===1&&t[0]<128?t:Buffer.concat([Yr(t.length,128),t]);let e=Buffer.concat(t.map(Dt));return Buffer.concat([Yr(e.length,192),e])}function Yr(t,e){if(t<56)return Buffer.from([e+t]);let r=z(t);return Buffer.concat([Buffer.from([e+55+r.length]),r])}function zr(t){let[e]=Zr(t,0);return e}function Zr(t,e){let r=t[e];if(r<128)return[Buffer.from([r]),e+1];if(r<=183){let i=r-128;return[t.subarray(e+1,e+1+i),e+1+i]}if(r<=191){let i=r-183,c=Xr(t.subarray(e+1,e+1+i)),l=e+1+i;return[t.subarray(l,l+c),l+c]}let n,o;if(r<=247)n=r-192,o=e+1;else{let i=r-247;n=Xr(t.subarray(e+1,e+1+i)),o=e+1+i}let s=[],a=o;for(;a<o+n;){let[i,c]=Zr(t,a);s.push(i),a=c}return[s,o+n]}function z(t){if(t===0||t===0n)return Buffer.alloc(0);if(t<0||t<0n)throw new Error("intToBuffer: negative values not supported");let e=t.toString(16),r=e.length%2?"0"+e:e;return Buffer.from(r,"hex")}function Xr(t){let e=0;for(let r of t)e=e*256+r;if(e>Number.MAX_SAFE_INTEGER)throw new Error("RLP length exceeds safe integer range");return e}var ws=1;async function j(t,e,r){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:ws++,method:e,params:r})});if(!n.ok)throw new Error(`RPC ${e}: HTTP ${n.status}`);let o=await n.json();if(o.error)throw new Error(`RPC ${e}: ${o.error?.message??JSON.stringify(o.error)}`);return o.result}async function Qr(t,e){let r=await j(t,"eth_getTransactionCount",[e,"pending"]);return parseInt(r,16)}async function en(t,e){let r=await j(t,"eth_estimateGas",[e]);return BigInt(r)}async function tn(t,e){let r=await j(t,"eth_chainId",[]),n=parseInt(r,16);if(n!==e)throw new Error(`chainId mismatch: RPC returned ${n}, expected ${e}. Wrong network?`)}async function rn(t){let[e,r]=await Promise.all([j(t,"eth_gasPrice",[]),j(t,"eth_maxPriorityFeePerGas",[]).catch(()=>"0x0")]),n=BigInt(e),o=BigInt(r);return{maxFeePerGas:n*2n+o,maxPriorityFeePerGas:o>0n?o:1000000n}}function Se(t,e){if(!t)return 0n;let[r,n=""]=t.split(".");if(n.length>e)throw new Error(`too many decimal places (max ${e}): ${t}`);return BigInt(r||"0")*10n**BigInt(e)+BigInt(n.padEnd(e,"0"))}var xs=[0x0000000000000001n,0x0000000000008082n,0x800000000000808an,0x8000000080008000n,0x000000000000808bn,0x0000000080000001n,0x8000000080008081n,0x8000000000008009n,0x000000000000008an,0x0000000000000088n,0x0000000080008009n,0x000000008000000an,0x000000008000808bn,0x800000000000008bn,0x8000000000008089n,0x8000000000008003n,0x8000000000008002n,0x8000000000000080n,0x000000000000800an,0x800000008000000an,0x8000000080008081n,0x8000000000008080n,0x0000000080000001n,0x8000000080008008n],bs=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]],ke=(1n<<64n)-1n;function nn(t,e){return(t<<BigInt(e)|t>>BigInt(64-e))&ke}function vs(t){for(let e=0;e<24;e++){let r=new Array(5);for(let o=0;o<5;o++)r[o]=t[o]^t[o+5]^t[o+10]^t[o+15]^t[o+20];for(let o=0;o<5;o++){let s=r[(o+4)%5]^nn(r[(o+1)%5],1);for(let a=0;a<25;a+=5)t[o+a]=(t[o+a]^s)&ke}let n=new Array(25);for(let o=0;o<5;o++)for(let s=0;s<5;s++)n[s+(2*o+3*s)%5*5]=nn(t[o+s*5],bs[o][s]);for(let o=0;o<25;o+=5)for(let s=0;s<5;s++)t[o+s]=(n[o+s]^~n[o+(s+1)%5]&ke&n[o+(s+2)%5])&ke;t[0]=(t[0]^xs[e])&ke}}function qt(t){let n=new Array(25).fill(0n),o=Buffer.alloc(Math.ceil((t.length+1)/136)*136);t.copy(o),o[t.length]=1,o[o.length-1]|=128;for(let a=0;a<o.length;a+=136){for(let i=0;i<17;i++){let c=0n,l=a+i*8;for(let u=7;u>=0;u--)c=c<<8n|BigInt(o[l+u]);n[i]^=c}vs(n)}let s=Buffer.alloc(32);for(let a=0;a<4;a++){let i=n[a];for(let c=0;c<8;c++)s[a*8+c]=Number(i&0xffn),i>>=8n}return s}function Es(t){let e=t.toLowerCase(),r=qt(Buffer.from(e)).toString("hex"),n="";for(let o=0;o<40;o++)n+=parseInt(r[o],16)>=8?e[o].toUpperCase():e[o];return n}function on(t){let e=t.replace(/^0x/,"");if(e.length!==40)return!1;let r=e.toLowerCase(),n=e.toUpperCase();return e===r||e===n?!0:e===Es(e)}var Ss=(1n<<256n)-1n;function Pe(t){if(!t)return 0n;let e;if(t.startsWith("0x"))e=BigInt(t);else{let r=t.toLowerCase();r.endsWith("ether")?e=Se(t.slice(0,-5),18):r.endsWith("gwei")?e=Se(t.slice(0,-4),9):e=BigInt(t)}if(e<0n)throw new Error(`value must not be negative: ${t}`);if(e>Ss)throw new Error(`value exceeds uint256 max: ${t}`);return e}async function sn(t,e){let{to:r,data:n,from:o}=e,s=r.replace(/^0x/,""),a=Buffer.from(s,"hex");if(a.length!==20)throw new Error(`invalid EVM address: ${r} (expected 20 bytes, got ${a.length})`);if(!on(r))throw new Error(`invalid EIP-55 checksum: ${r}`);let i=e.value?Pe(e.value):0n,c=e.nonce;if(c===void 0){if(!o)throw new Error("--from is required when --nonce is not specified (needed for nonce lookup)");c=await Qr(t.rpc,o)}let{gasLimit:l,maxFeePerGas:u,maxPriorityFeePerGas:d}=e;if(!l||!u){let g=await rn(t.rpc);u??=g.maxFeePerGas,d??=g.maxPriorityFeePerGas,l||(l=await en(t.rpc,{from:o,to:r,value:i>0n?"0x"+i.toString(16):void 0,data:n||void 0}),l=l*12n/10n)}d??=1000000n;let p=[z(t.chainId),z(c),z(d),z(u),z(l),Buffer.from(r.replace(/^0x/,""),"hex"),z(i),n?Buffer.from(n.replace(/^0x/,""),"hex"):Buffer.alloc(0),[]];return"0x02"+Dt(p).toString("hex")}function an(t){if(!t.startsWith("0x02"))throw new Error("only EIP-1559 (type 2) transactions supported");let e=Buffer.from(t.slice(4),"hex"),r=zr(e);if(!Array.isArray(r)||r.length<9)throw new Error("invalid EIP-1559 transaction");let n=s=>Buffer.isBuffer(s)?s:Buffer.alloc(0),o=s=>{let a=n(s);return a.length===0?"0":BigInt("0x"+a.toString("hex")).toString()};return{chainId:o(r[0]),nonce:o(r[1]),maxPriorityFeePerGas:o(r[2]),maxFeePerGas:o(r[3]),gasLimit:o(r[4]),to:"0x"+n(r[5]).toString("hex"),value:o(r[6]),data:n(r[7]).length>0?"0x"+n(r[7]).toString("hex"):"0x"}}import{publicEncrypt as ks,constants as Ps}from"node:crypto";var $s=`-----BEGIN PUBLIC KEY-----
|
|
153
153
|
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA2Fxydgm/ryYk0IexQIuL
|
|
154
154
|
9DKyiIk2WmS36AZ83a9Z0QX53qdveg08b05g1Qr+o+COoYOT/FDi8anRGAs7rIyS
|
|
155
155
|
uigrjHR6VrmFjnGrrTr3MINwC9cYQFHwET8YVGRq+BB3iFTB1kIb9XJ/vT2sk1xP
|
|
@@ -162,8 +162,8 @@ nrK/O/SVDtT1ohp2F+Zg1mojTgKfLOyGdOUXTi95naDTuG770rSjHdL80tJBz1Fd
|
|
|
162
162
|
rOluAFalaKynyH3KMyRg+NuLmibu5OmcMjCLK3D4X1YLiN2OK8/bbpEL8JYroDwb
|
|
163
163
|
EXIUW5mGS06YxfSUsxHzL9Tj00+GMm/Gvl0+4/+Vn8IXVHjQOSPNEy3EnqCiH/OW
|
|
164
164
|
8v0IMC32CeGrX7mGbU+MzlsCAwEAAQ==
|
|
165
|
-
-----END PUBLIC KEY-----`;function
|
|
166
|
-
`);let w=!1;if(e.destATAExists!==void 0)w=!e.destATAExists;else if(t.rpc)try{w=!(await Tt(t.rpc,Z(c.address))).exists}catch{w=!0}let S=[],g=[];function m(k,U,G){let ee=Z(k),I=g.find(te=>Z(te.key)===ee);I?(I.isSigner=I.isSigner||U,I.isWritable=I.isWritable||G):g.push({key:Buffer.from(k),isSigner:U,isWritable:G})}w&&(m(s,!0,!0),m(c.address,!1,!0),m(a,!1,!1),m(i,!1,!1),m(_t,!1,!1),m(Pe,!1,!1),m(Ze,!1,!1)),m(s,!0,!0),m(l.address,!1,!0),m(i,!1,!1),m(c.address,!1,!0),m(Pe,!1,!1),g.sort((k,U)=>{let G=(k.isSigner?0:2)+(k.isWritable?0:1),ee=(U.isSigner?0:2)+(U.isWritable?0:1);return G-ee});let E=g.map(k=>k.key);function b(k){let U=Z(k),G=g.findIndex(ee=>Z(ee.key)===U);if(G<0)throw new Error(`account not found in list: ${U}`);return G}let x=0,R=0,O=0;for(let k of g)k.isSigner?(x++,k.isWritable||R++):k.isWritable||O++;if(w){let k=Buffer.concat([Buffer.from([b(Ze)]),N(7),Buffer.from([b(s),b(c.address),b(a),b(i),b(_t),b(Pe),b(Ze)]),N(0)]);S.push(k)}let $=Buffer.alloc(10);$[0]=12,$.writeBigUInt64LE(f,1),$[9]=d;let C=Buffer.concat([Buffer.from([b(Pe)]),N(4),Buffer.from([b(l.address),b(i),b(c.address),b(s)]),N($.length),$]);S.push(C);let P=Buffer.from([x,R,O]),A=Buffer.concat([P,N(E.length),...E,u,N(S.length),...S]),v=Buffer.concat([Buffer.from([128]),A,N(0)]);return Buffer.concat([N(x),...Array.from({length:x},()=>Buffer.alloc(64)),v]).toString("base64")}function rn(t){let e=Buffer.from(t,"base64"),r=0,[n,o]=pe(e,r);r=o,r+=n*64;let s="legacy";e[r]===128&&(s=0,r++);let a=e[r++],i=e[r++],l=e[r++],[c,u]=pe(e,r);r=u;let d=[];for(let b=0;b<c;b++)d.push(Z(e.subarray(r,r+32))),r+=32;let p=Z(e.subarray(r,r+32));r+=32;let[f,w]=pe(e,r);r=w;let S={version:s,numSignatures:n,numRequiredSignatures:a,accounts:d,blockhash:p,numInstructions:f},g="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",m="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",E=[];for(let b=0;b<f;b++){let x=e[r++],[R,O]=pe(e,r);r=O;let $=[];for(let _=0;_<R;_++)$.push(e[r++]);let[C,P]=pe(e,r);r=P;let A=e.subarray(r,r+C);r+=C;let v={program:d[x]||`index:${x}`,accounts:$.map(_=>d[_]||`index:${_}`)};x<c&&d[x]==="11111111111111111111111111111111"&&C===12&&A.readUInt32LE(0)===2&&(v.type="transfer",v.lamports=A.readBigUInt64LE(4).toString(),v.from=d[$[0]],v.to=d[$[1]]),x<c&&d[x]===m&&C===0&&(v.type="createAssociatedTokenAccount",v.payer=d[$[0]],v.ata=d[$[1]],v.owner=d[$[2]],v.mint=d[$[3]]),x<c&&d[x]===g&&C===10&&A[0]===12&&(v.type="transferChecked",v.amount=A.readBigUInt64LE(1).toString(),v.decimals=A[9],v.source=d[$[0]],v.mint=d[$[1]],v.destination=d[$[2]],v.authority=d[$[3]]),E.push(v)}return E.length===1&&(S.instruction=E[0]),E.length>0&&(S.instructions=E),S}function cs(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]*)\)$/);if(!e)throw new Error(`invalid function signature: ${t}`);let r=e[1],n=e[2]===""?[]:e[2].split(",").map(o=>o.trim());return{name:r,types:n}}function ls(t){return Pt(Buffer.from(t)).subarray(0,4)}function nn(t,e){if(t==="address"){if(!e.startsWith("0x"))throw new Error(`address must be 0x-prefixed: ${e}`);let r=e.slice(2).toLowerCase().padStart(40,"0");if(r.length!==40)throw new Error(`invalid address length: ${e}`);return Buffer.from(r.padStart(64,"0"),"hex")}if(t==="bool")return Re(e==="true"||e==="1"?1n:0n);if(t.startsWith("uint")){let r=on(e);if(r<0n)throw new Error(`uint value must be non-negative: ${e}`);return Re(r)}if(t.startsWith("int")){let r=on(e),n=r<0n?(1n<<256n)+r:r;return Re(n)}if(t.startsWith("bytes")&&t!=="bytes"){let r=parseInt(t.slice(5),10);if(r<1||r>32)throw new Error(`invalid fixed bytes size: ${t}`);let n=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(n,"hex");if(o.length>r)throw new Error(`${t} value too long: ${o.length} bytes`);let s=Buffer.alloc(32);return o.copy(s,0),s}if(t==="string")return sn(Buffer.from(e,"utf8"));if(t==="bytes"){let r=e.startsWith("0x")?e.slice(2):e;return sn(Buffer.from(r,"hex"))}throw new Error(`unsupported ABI type: ${t}`)}function an(t){return/^[a-zA-Z_][a-zA-Z0-9_]*\(/.test(t)}function cn(t){return t===""?[]:t.split(",").map(e=>e.trim())}function ln(t,e){if(e.length!==t.length)throw new Error(`expected ${t.length} argument(s) for (${t.join(",")}), got ${e.length}`);return"0x"+dn(t,e).toString("hex")}function un(t,e){let{types:r}=cs(t);if(e.length!==r.length)throw new Error(`expected ${r.length} argument(s) for ${t}, got ${e.length}`);let n=ls(t);return"0x"+Buffer.concat([n,dn(r,e)]).toString("hex")}function dn(t,e){let r=i=>i==="string"||i==="bytes"||i.endsWith("[]"),n=t.length*32,o=[],s=[];for(let i=0;i<t.length;i++)r(t[i])?(o.push(Buffer.alloc(32)),s.push(nn(t[i],e[i]))):(o.push(nn(t[i],e[i])),s.push(Buffer.alloc(0)));let a=n;for(let i=0;i<t.length;i++)r(t[i])&&(o[i]=Re(BigInt(a)),a+=s[i].length);return Buffer.concat([...o,...s])}function Re(t){let e=(t&(1n<<256n)-1n).toString(16).padStart(64,"0");return Buffer.from(e,"hex")}function on(t){return t.startsWith("0x")||t.startsWith("0X")?BigInt(t):t.startsWith("-0x")||t.startsWith("-0X")?-BigInt(t.slice(1)):BigInt(t)}function sn(t){let e=Re(BigInt(t.length)),r=Math.ceil(t.length/32)*32,n=Buffer.alloc(r);return t.copy(n),Buffer.concat([e,n])}async function pn(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t)}var ds=`Client-side utilities
|
|
165
|
+
-----END PUBLIC KEY-----`;function cn(t){let e=t.startsWith("0x")?t.slice(2):t,r=/^[0-9a-fA-F]+$/.test(e);return ks({key:$s,padding:Ps.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r?e:t,r?"hex":"utf8")).toString("base64")}import{createHash as As}from"node:crypto";var Mt="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Lt=BigInt(Mt.length),Rs=new Map(Mt.split("").map((t,e)=>[t,BigInt(e)]));function T(t){let e=0n;for(let o of t){let s=Rs.get(o);if(s===void 0)throw new Error(`invalid base58 character: ${o}`);e=e*Lt+s}let r=e===0n?Buffer.alloc(0):Buffer.from(e.toString(16).padStart(e.toString(16).length+e.toString(16).length%2,"0"),"hex"),n=0;for(let o of t)if(o==="1")n++;else break;return Buffer.concat([Buffer.alloc(n),r])}function U(t){let e=0n;for(let n of t)e=e*256n+BigInt(n);let r="";for(;e>0n;){let[n,o]=[e/Lt,e%Lt];r=Mt[Number(o)]+r,e=n}for(let n of t)if(n===0)r="1"+r;else break;return r}function k(t){if(t<0||t>65535)throw new Error(`compactU16 out of range: ${t}`);return t<128?Buffer.from([t]):t<16384?Buffer.from([t&127|128,t>>7]):Buffer.from([t&127|128,t>>7&127|128,t>>14])}function ce(t,e){let r=0,n=0,o=e;for(let s=0;s<3;s++){let a=t[o++];if(r|=(a&127)<<n,(a&128)===0)return[r,o];n+=7}return[r,o]}async function $e(t){return(await j(t,"getLatestBlockhash",[{commitment:"finalized"}])).value.blockhash}async function ln(t,e){let r=await j(t,"getBalance",[e,{commitment:"confirmed"}]);return BigInt(r.value)}async function un(t,e){let r=await j(t,"getMinimumBalanceForRentExemption",[e]);return BigInt(r)}async function Re(t,e){let r=await j(t,"getAccountInfo",[e,{encoding:"base64",commitment:"confirmed"}]);return r.value?{exists:!0,data:Buffer.from(r.value.data[0],"base64"),owner:r.value.owner,lamports:r.value.lamports}:{exists:!1,data:Buffer.alloc(0),owner:"",lamports:0}}var le=class{metas=[];add(e,r,n){let o=U(e),s=this.metas.find(a=>U(a.key)===o);s?(s.isSigner=s.isSigner||r,s.isWritable=s.isWritable||n):this.metas.push({key:Buffer.from(e),isSigner:r,isWritable:n})}sort(){this.metas.sort((e,r)=>{let n=(e.isSigner?0:2)+(e.isWritable?0:1),o=(r.isSigner?0:2)+(r.isWritable?0:1);return n-o})}ensureFirst(e){let r=U(e),n=this.metas.findIndex(o=>U(o.key)===r);if(n>0){let[o]=this.metas.splice(n,1);this.metas.unshift(o)}}indexOf(e){let r=U(e),n=this.metas.findIndex(o=>U(o.key)===r);if(n<0)throw new Error(`account not found: ${r}`);return n}get keys(){return this.metas.map(e=>e.key)}get header(){let e=0,r=0,n=0;for(let o of this.metas)o.isSigner?(e++,o.isWritable||r++):o.isWritable||n++;return{numRequiredSignatures:e,numReadonlySigned:r,numReadonlyUnsigned:n}}get length(){return this.metas.length}};function ot(t,e,r){let{numRequiredSignatures:n,numReadonlySigned:o,numReadonlyUnsigned:s}=t.header,a=Buffer.from([n,o,s]),i=Buffer.concat([a,k(t.length),...t.keys,e,k(r.length),...r]),c=Buffer.concat([Buffer.from([128]),i,k(0)]);return Buffer.concat([k(n),...Array.from({length:n},()=>Buffer.alloc(64)),c])}var jt=Buffer.alloc(32),Z=T("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),st=T("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"),at=(1n<<64n)-1n;function ct(t){if(!t)return 0n;let e;if(t.toLowerCase().endsWith("sol")?e=Se(t.slice(0,-3),9):e=BigInt(t),e<0n)throw new Error(`value must not be negative: ${t}`);if(e>at)throw new Error(`value exceeds u64 max: ${t}`);return e}async function dn(t,e){let{from:r,to:n}=e;if(!r)throw new Error("--from is required");if(!n)throw new Error("--to is required");let o=e.value?ct(e.value):0n,s=T(r);if(s.length!==32)throw new Error(`invalid Solana address: ${r} (expected 32 bytes, got ${s.length})`);let a=T(n);if(a.length!==32)throw new Error(`invalid Solana address: ${n} (expected 32 bytes, got ${a.length})`);let i;if(e.blockhash)i=T(e.blockhash);else{let h=await $e(t.rpc);i=T(h)}let c=Buffer.alloc(12);c.writeUInt32LE(2,0),c.writeBigUInt64LE(o,4);let l=[s,a,jt],u=Buffer.from([1,0,1]),d=Buffer.concat([Buffer.from([2]),k(2),Buffer.from([0,1]),k(c.length),c]),p=Buffer.concat([u,k(l.length),...l,i,k(1),d]),f=Buffer.concat([Buffer.from([128]),p,k(0)]);return Buffer.concat([k(1),Buffer.alloc(64),f]).toString("base64")}function Ts(t,e){for(let r=255;r>=0;r--){let n=As("sha256");for(let s of t)n.update(s);n.update(Buffer.from([r])),n.update(e),n.update(Buffer.from("ProgramDerivedAddress"));let o=n.digest();if(!_s(o))return{address:o,bump:r}}throw new Error("Could not find PDA")}var G=2n**255n-19n,Is=-121665n*fn(121666n,G)%G;function it(t,e){return(t%e+e)%e}function pn(t,e,r){let n=1n;for(t=it(t,r);e>0n;)e&1n&&(n=n*t%r),e>>=1n,t=t*t%r;return n}function fn(t,e){return pn(t,e-2n,e)}function _s(t){let e=0n;for(let o=31;o>=0;o--)e=e<<8n|BigInt(t[o]);if(e&=(1n<<255n)-1n,e>=G)return!1;let r=it(e*e,G),n=it((r-1n)*fn(it(Is*r+1n,G),G),G);return n===0n?!0:pn(n,(G-1n)/2n,G)===1n}function Ae(t,e){return Ts([t,Z,e],st)}function Ut(t){if(t.length<45)throw new Error("invalid mint account data (too short)");return t[44]}async function mn(t,e){let{from:r,to:n,mint:o}=e;if(!r)throw new Error("--from is required");if(!n)throw new Error("--to is required");if(!o)throw new Error("--token is required");let s=T(r),a=T(n),i=T(o),c=Ae(s,i),l=Ae(a,i),u;if(e.blockhash)u=T(e.blockhash);else{let S=await $e(t.rpc);u=T(S)}let d;if(e.decimals!==void 0)d=e.decimals;else{let S=await Re(t.rpc,o);if(!S.exists)throw new Error(`mint account not found: ${o}`);d=Ut(S.data)}let p=e.value||"0";if(p.toLowerCase().endsWith("sol"))throw new Error('--value with "sol" suffix cannot be used with --token (use atomic token units)');let f=BigInt(p);if(f<0n)throw new Error(`value must not be negative: ${p}`);if(f>at)throw new Error(`value exceeds u64 max: ${p}`);process.stderr.write(`Amount: ${f} token units (decimals: ${d})
|
|
166
|
+
`);let g=!1;if(e.destATAExists!==void 0)g=!e.destATAExists;else if(t.rpc)try{g=!(await Re(t.rpc,U(l.address))).exists}catch{g=!0}let h=new le;g&&(h.add(s,!0,!0),h.add(l.address,!1,!0),h.add(a,!1,!1),h.add(i,!1,!1),h.add(jt,!1,!1),h.add(Z,!1,!1),h.add(st,!1,!1)),h.add(s,!0,!0),h.add(c.address,!1,!0),h.add(i,!1,!1),h.add(l.address,!1,!0),h.add(Z,!1,!1),h.sort();let y=[];g&&y.push(Buffer.concat([Buffer.from([h.indexOf(st)]),k(7),Buffer.from([h.indexOf(s),h.indexOf(l.address),h.indexOf(a),h.indexOf(i),h.indexOf(jt),h.indexOf(Z),h.indexOf(st)]),k(0)]));let m=Buffer.alloc(10);return m[0]=12,m.writeBigUInt64LE(f,1),m[9]=d,y.push(Buffer.concat([Buffer.from([h.indexOf(Z)]),k(4),Buffer.from([h.indexOf(c.address),h.indexOf(i),h.indexOf(l.address),h.indexOf(s)]),k(m.length),m])),ot(h,u,y).toString("base64")}function gn(t){let e=Buffer.from(t,"base64"),r=0,[n,o]=ce(e,r);r=o,r+=n*64;let s="legacy";e[r]===128&&(s=0,r++);let a=e[r++],i=e[r++],c=e[r++],[l,u]=ce(e,r);r=u;let d=[];for(let S=0;S<l;S++)d.push(U(e.subarray(r,r+32))),r+=32;let p=U(e.subarray(r,r+32));r+=32;let[f,g]=ce(e,r);r=g;let h={version:s,numSignatures:n,numRequiredSignatures:a,accounts:d,blockhash:p,numInstructions:f},y="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",m="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",v=[];for(let S=0;S<f;S++){let b=e[r++],[I,N]=ce(e,r);r=N;let R=[];for(let _=0;_<I;_++)R.push(e[r++]);let[O,P]=ce(e,r);r=P;let A=e.subarray(r,r+O);r+=O;let E={program:d[b]||`index:${b}`,accounts:R.map(_=>d[_]||`index:${_}`)};b<l&&d[b]==="11111111111111111111111111111111"&&O===12&&A.readUInt32LE(0)===2&&(E.type="transfer",E.lamports=A.readBigUInt64LE(4).toString(),E.from=d[R[0]],E.to=d[R[1]]),b<l&&d[b]===m&&O===0&&(E.type="createAssociatedTokenAccount",E.payer=d[R[0]],E.ata=d[R[1]],E.owner=d[R[2]],E.mint=d[R[3]]),b<l&&d[b]===y&&O===10&&A[0]===12&&(E.type="transferChecked",E.amount=A.readBigUInt64LE(1).toString(),E.decimals=A[9],E.source=d[R[0]],E.mint=d[R[1]],E.destination=d[R[2]],E.authority=d[R[3]]),v.push(E)}return v.length===1&&(h.instruction=v[0]),v.length>0&&(h.instructions=v),h}function Os(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]*)\)$/);if(!e)throw new Error(`invalid function signature: ${t}`);let r=e[1],n=e[2]===""?[]:e[2].split(",").map(o=>o.trim());return{name:r,types:n}}function Cs(t){return qt(Buffer.from(t)).subarray(0,4)}function hn(t,e){if(t==="address"){if(!e.startsWith("0x"))throw new Error(`address must be 0x-prefixed: ${e}`);let r=e.slice(2).toLowerCase().padStart(40,"0");if(r.length!==40)throw new Error(`invalid address length: ${e}`);return Buffer.from(r.padStart(64,"0"),"hex")}if(t==="bool")return Te(e==="true"||e==="1"?1n:0n);if(t.startsWith("uint")){let r=yn(e);if(r<0n)throw new Error(`uint value must be non-negative: ${e}`);return Te(r)}if(t.startsWith("int")){let r=yn(e),n=r<0n?(1n<<256n)+r:r;return Te(n)}if(t.startsWith("bytes")&&t!=="bytes"){let r=parseInt(t.slice(5),10);if(r<1||r>32)throw new Error(`invalid fixed bytes size: ${t}`);let n=e.startsWith("0x")?e.slice(2):e,o=Buffer.from(n,"hex");if(o.length>r)throw new Error(`${t} value too long: ${o.length} bytes`);let s=Buffer.alloc(32);return o.copy(s,0),s}if(t==="string")return wn(Buffer.from(e,"utf8"));if(t==="bytes"){let r=e.startsWith("0x")?e.slice(2):e;return wn(Buffer.from(r,"hex"))}throw new Error(`unsupported ABI type: ${t}`)}function xn(t){return/^[a-zA-Z_][a-zA-Z0-9_]*\(/.test(t)}function bn(t){return t===""?[]:t.split(",").map(e=>e.trim())}function vn(t,e){if(e.length!==t.length)throw new Error(`expected ${t.length} argument(s) for (${t.join(",")}), got ${e.length}`);return"0x"+Sn(t,e).toString("hex")}function En(t,e){let{types:r}=Os(t);if(e.length!==r.length)throw new Error(`expected ${r.length} argument(s) for ${t}, got ${e.length}`);let n=Cs(t);return"0x"+Buffer.concat([n,Sn(r,e)]).toString("hex")}function Sn(t,e){let r=i=>i==="string"||i==="bytes"||i.endsWith("[]"),n=t.length*32,o=[],s=[];for(let i=0;i<t.length;i++)r(t[i])?(o.push(Buffer.alloc(32)),s.push(hn(t[i],e[i]))):(o.push(hn(t[i],e[i])),s.push(Buffer.alloc(0)));let a=n;for(let i=0;i<t.length;i++)r(t[i])&&(o[i]=Te(BigInt(a)),a+=s[i].length);return Buffer.concat([...o,...s])}function Te(t){let e=(t&(1n<<256n)-1n).toString(16).padStart(64,"0");return Buffer.from(e,"hex")}function yn(t){return t.startsWith("0x")||t.startsWith("0X")?BigInt(t):t.startsWith("-0x")||t.startsWith("-0X")?-BigInt(t.slice(1)):BigInt(t)}function wn(t){let e=Te(BigInt(t.length)),r=Math.ceil(t.length/32)*32,n=Buffer.alloc(r);return t.copy(n),Buffer.concat([e,n])}async function lt(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t)}import{randomBytes as kn}from"node:crypto";var Bs="0x000000000022D473030F116dDEE9F6B43aC78BA3",Ns="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Ds="0x4020A4f3b7b90ccA423B9fabCc0CE57C6C240002",qs={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},Ls={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},Ms={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"facilitator",type:"address"},{name:"validAfter",type:"uint256"}]};function Pn(){return"0x"+kn(32).toString("hex")}function $n(){return BigInt("0x"+kn(32).toString("hex")).toString()}function Ft(t,e){let r=nt(t.network),n=Pn(),o=Math.floor(Date.now()/1e3);if(!t.extra?.name||!t.extra?.version)throw new Error("EIP-712 domain parameters (name, version) are required in payment requirements extra");return{types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...qs},primaryType:"TransferWithAuthorization",domain:{name:t.extra.name,version:t.extra.version,chainId:r,verifyingContract:t.asset},message:{from:e,to:t.payTo,value:t.amount,validAfter:String(o-600),validBefore:String(o+t.maxTimeoutSeconds),nonce:n}}}function Wt(t,e,r){let n=nt(t.network),o=$n(),s=Math.floor(Date.now()/1e3),a=String(s-600),i=String(s+t.maxTimeoutSeconds),c=r||t.amount,l=t.scheme==="upto";if(l&&!t.extra?.facilitatorAddress)throw new Error("upto scheme requires extra.facilitatorAddress in payment requirements");let u={to:t.payTo,validAfter:a};return l&&(u.facilitator=t.extra.facilitatorAddress),{types:{EIP712Domain:[{name:"name",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...l?Ms:Ls},primaryType:"PermitWitnessTransferFrom",domain:{name:"Permit2",chainId:n,verifyingContract:Bs},message:{permitted:{token:t.asset,amount:c},spender:l?Ds:Ns,nonce:o,deadline:i,witness:u}}}import{randomBytes as js}from"node:crypto";var Ht=T("ComputeBudget111111111111111111111111111111"),Rn=T("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Us=2e4,Fs=1n,An=256;function Tn(t){let e=Buffer.alloc(5);return e[0]=2,e.writeUInt32LE(t,1),e}function In(t){let e=Buffer.alloc(9);return e[0]=3,e.writeBigUInt64LE(t,1),e}async function Vt(t,e,r){if(!t.extra?.feePayer)throw new Error("feePayer is required in payment requirements extra for Solana x402");let n=Kr(t.network);if(!n)throw new Error(`unsupported Solana network: ${t.network}`);let o=T(e),s=T(t.extra.feePayer),a=T(t.payTo),i=T(t.asset),c=Ae(o,i),l=Ae(a,i),u;r?.blockhash?u=T(r.blockhash):u=T(await $e(n.rpc));let d;if(r?.decimals!==void 0)d=r.decimals;else{let b=await Re(n.rpc,t.asset);if(!b.exists)throw new Error(`mint account not found: ${t.asset}`);d=Ut(b.data)}let p=BigInt(t.amount);if(p<0n)throw new Error(`amount must not be negative: ${t.amount}`);if(p>at)throw new Error(`amount exceeds u64 max: ${t.amount}`);let f;if(t.extra.memo){if(f=Buffer.from(t.extra.memo,"utf-8"),f.length>An)throw new Error(`memo exceeds maximum ${An} bytes`)}else f=Buffer.from(js(16).toString("hex"),"utf-8");let g=new le;g.add(s,!0,!0),g.add(o,!0,!0),g.add(c.address,!1,!0),g.add(i,!1,!1),g.add(l.address,!1,!0),g.add(Z,!1,!1),g.add(Ht,!1,!1),g.add(Rn,!1,!1),g.sort(),g.ensureFirst(s);let h=[],y=Tn(Us);h.push(Buffer.concat([Buffer.from([g.indexOf(Ht)]),k(0),k(y.length),y]));let m=In(Fs);h.push(Buffer.concat([Buffer.from([g.indexOf(Ht)]),k(0),k(m.length),m]));let v=Buffer.alloc(10);return v[0]=12,v.writeBigUInt64LE(p,1),v[9]=d,h.push(Buffer.concat([Buffer.from([g.indexOf(Z)]),k(4),Buffer.from([g.indexOf(c.address),g.indexOf(i),g.indexOf(l.address),g.indexOf(o)]),k(v.length),v])),h.push(Buffer.concat([Buffer.from([g.indexOf(Rn)]),k(0),k(f.length),f])),{transaction:ot(g,u,h).toString("base64")}}function Gt(t){let e;try{e=JSON.parse(t)}catch{throw new Error("invalid payment requirements JSON")}if(Array.isArray(e)){if(e.length===0)throw new Error("payment requirements array is empty");e=e[0]}let{scheme:r,asset:n,amount:o,payTo:s,maxTimeoutSeconds:a,extra:i}=e;if(!r)throw new Error('payment requirements missing "scheme"');if(!e.network)throw new Error('payment requirements missing "network"');if(!n)throw new Error('payment requirements missing "asset"');if(o==null)throw new Error('payment requirements missing "amount"');if(!s)throw new Error('payment requirements missing "payTo"');let c=Nt(e.network);if(!c.startsWith("eip155:")&&!c.startsWith("solana:"))throw new Error(`unsupported network: ${e.network}. Expected eip155:<chainId>, solana:<genesisHash>, or a known name (base, solana, etc.)`);return{scheme:r,network:c,networkRaw:e.network,asset:n,amount:String(o),payTo:s,maxTimeoutSeconds:a??60,extra:i??{}}}function _n(t,e,r,n=1){let o=Ee(t.network)?{transaction:r}:{signature:r,authorization:e};return n===1?{x402Version:1,scheme:t.scheme,network:t.networkRaw,payload:o}:{x402Version:n,payload:o,accepted:{scheme:t.scheme,network:t.networkRaw,asset:t.asset,amount:t.amount,payTo:t.payTo,maxTimeoutSeconds:t.maxTimeoutSeconds,extra:t.extra}}}function On(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function Cn(t){if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("invalid base64 in payment header");return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}var Hs=`Client-side utilities
|
|
167
167
|
|
|
168
168
|
Usage:
|
|
169
169
|
cdp util <command> [flags]
|
|
@@ -173,9 +173,10 @@ Commands:
|
|
|
173
173
|
tx-decode Decode a raw transaction hex or base64
|
|
174
174
|
abi-encode Encode ABI data \u2014 function calls or raw values
|
|
175
175
|
encrypt-key Encrypt a private key for account import
|
|
176
|
+
x402 x402 payment utilities (build, encode, decode)
|
|
176
177
|
|
|
177
178
|
Run 'cdp util <command> -h' for command-specific help.
|
|
178
|
-
`,
|
|
179
|
+
`,Vs=`Build an unsigned transaction
|
|
179
180
|
|
|
180
181
|
Supports EVM networks (base, ethereum, arbitrum, optimism, polygon, avalanche)
|
|
181
182
|
and Solana networks (solana, solana-devnet). Chain is auto-detected from --network.
|
|
@@ -205,14 +206,14 @@ EVM examples:
|
|
|
205
206
|
Solana examples:
|
|
206
207
|
cdp util tx-encode --network solana-devnet --from <base58> --to <base58> --value 0.5sol
|
|
207
208
|
cdp util tx-encode --network solana-devnet --from <base58> --to <base58> --value 1000000 --token <mint>
|
|
208
|
-
`;function
|
|
209
|
-
`);return}throw new Error(`unknown util command: ${e}
|
|
210
|
-
Run: cdp util --help`)}async function
|
|
211
|
-
`)}let d=!
|
|
212
|
-
`)}catch{}let p;
|
|
213
|
-
`);return}if(s.chain!=="evm")throw new Error(`unsupported chain: ${s.chain}`);let a=e.flags.value,i=a?
|
|
214
|
-
`),s.rpc&&(o||e.flags.nonce===void 0))try{await
|
|
215
|
-
`)}var
|
|
209
|
+
`;function Bn(t,e){if(e==="solana"){let r=Number(t)/1e9;return`${t} lamports (${r} SOL)`}if(t>=1000000000000000n){let r=Number(t)/1e18;return`${t} wei (${r} ETH)`}if(t>=1000000n){let r=Number(t)/1e9;return`${t} wei (${r} gwei)`}return`${t} wei`}async function Dn(t){if(t.length===0||t[0]==="-h"||t[0]==="--help"){process.stderr.write(Hs);return}let[e,...r]=t;if(e==="tx-encode")return Gs(r);if(e==="tx-decode")return ni(r);if(e==="abi-encode")return ri(r);if(e==="encrypt-key"){if(r[0]==="-h"||r[0]==="--help"||r.length===0){process.stderr.write(Nn),r[0]!=="-h"&&r[0]!=="--help"&&process.exit(1);return}let n=L(r,[["file","f",!0]]),o;if(n.flags.file)try{o=Ws(n.flags.file,"utf-8").trim()}catch{throw new Error(`cannot read key file: ${n.flags.file}`)}else if(n.args[0]==="-"||!process.stdin.isTTY)o=(await lt()).toString("utf-8").trim();else{process.stderr.write(Nn),process.exit(1);return}if(!o)throw new Error("private key cannot be empty");process.stdout.write(cn(o)+`
|
|
210
|
+
`);return}if(e==="x402")return Zs(r);throw new Error(`unknown util command: ${e}
|
|
211
|
+
Run: cdp util --help`)}async function Gs(t){let e=L(t,[["network","n",!0],["to",null,!0],["value",null,!0],["data","d",!0],["from",null,!0],["nonce",null,!0],["gas-limit",null,!0],["max-fee",null,!0],["max-priority-fee",null,!0],["rpc-url",null,!0],["blockhash",null,!0],["token",null,!0]]);if(e.help){process.stderr.write(Vs);return}let r=e.flags.network,n=e.flags.to,o=e.flags.from;if(!r)throw new Error("--network is required");if(!n)throw new Error("--to is required");let s=Jr(r,e.flags["rpc-url"]);if(s.chain==="solana"){if(!o)throw new Error("--from is required");let l=e.flags.token,u=e.flags.value;if(!l){let f=u?ct(u):0n;f>0n&&process.stderr.write(`Value: ${Bn(f,"solana")}
|
|
212
|
+
`)}let d=!l&&u?ct(u):0n;if(!l&&d>0n&&s.rpc)try{let[f,g]=await Promise.all([ln(s.rpc,o),un(s.rpc,0)]),h=f-d;h>0n&&h<g&&process.stderr.write(`warning: sender will have ${h} lamports remaining, below rent-exempt minimum (${g}). Account may be garbage-collected.
|
|
213
|
+
`)}catch{}let p;l?p=await mn(s,{from:o,to:n,value:e.flags.value,blockhash:e.flags.blockhash,mint:l}):p=await dn(s,{from:o,to:n,value:e.flags.value,blockhash:e.flags.blockhash}),process.stdout.write(p+`
|
|
214
|
+
`);return}if(s.chain!=="evm")throw new Error(`unsupported chain: ${s.chain}`);let a=e.flags.value,i=a?Pe(a):0n;if(i>0n&&process.stderr.write(`Value: ${Bn(i,"evm")}
|
|
215
|
+
`),s.rpc&&(o||e.flags.nonce===void 0))try{await tn(s.rpc,s.chainId)}catch(l){throw new Error(l.message)}let c=await sn(s,{to:n,value:e.flags.value,data:e.flags.data,from:o,nonce:e.flags.nonce!==void 0?parseInt(e.flags.nonce,10):void 0,gasLimit:e.flags["gas-limit"]?BigInt(e.flags["gas-limit"]):void 0,maxFeePerGas:e.flags["max-fee"]?Pe(e.flags["max-fee"]):void 0,maxPriorityFeePerGas:e.flags["max-priority-fee"]?Pe(e.flags["max-priority-fee"]):void 0});process.stdout.write(c+`
|
|
216
|
+
`)}var Js=`Encode ABI data \u2014 function calls or raw values
|
|
216
217
|
|
|
217
218
|
Usage:
|
|
218
219
|
cdp util abi-encode <signature-or-types> [args...]
|
|
@@ -231,7 +232,7 @@ Examples:
|
|
|
231
232
|
cdp util abi-encode "balanceOf(address)" 0xAccount
|
|
232
233
|
cdp util abi-encode "address,uint256" 0xSpender 1000
|
|
233
234
|
cdp util abi-encode "uint8,bytes" 0 0xdeadbeef
|
|
234
|
-
`,
|
|
235
|
+
`,Nn=`Encrypt a private key for account import
|
|
235
236
|
|
|
236
237
|
Usage:
|
|
237
238
|
cdp util encrypt-key --file <path>
|
|
@@ -251,42 +252,101 @@ Output: base64 ciphertext for the encryptedPrivateKey field.
|
|
|
251
252
|
Examples:
|
|
252
253
|
cdp util encrypt-key --file ./exported-key.txt
|
|
253
254
|
vault kv get -field=key secret/wallet | cdp util encrypt-key -
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
255
|
+
`,Ks=`x402 payment utilities
|
|
256
|
+
|
|
257
|
+
Usage:
|
|
258
|
+
cdp util x402 <command> [flags]
|
|
259
|
+
|
|
260
|
+
Commands:
|
|
261
|
+
build Build signing payload from payment requirements
|
|
262
|
+
encode Encode payment payload as base64 header
|
|
263
|
+
decode Decode a base64 payment header
|
|
264
|
+
|
|
265
|
+
Run 'cdp util x402 <command> -h' for command-specific help.
|
|
266
|
+
`,Ys=`Build signing payload from payment requirements
|
|
267
|
+
|
|
268
|
+
Usage:
|
|
269
|
+
cdp util x402 build --from <address> --payment-requirements '<json>' [--amount N]
|
|
270
|
+
echo '<json>' | cdp util x402 build --from <address>
|
|
271
|
+
|
|
272
|
+
Flags:
|
|
273
|
+
--from <address> Sender address (EVM 0x... or Solana base58)
|
|
274
|
+
--payment-requirements <json> Payment requirements JSON (V2)
|
|
275
|
+
--amount <value> Override amount (permit2 scheme only)
|
|
276
|
+
|
|
277
|
+
Chain is auto-detected from the network field in payment requirements
|
|
278
|
+
(eip155:* for EVM, solana:* for Solana).
|
|
279
|
+
|
|
280
|
+
Outputs JSON to stdout:
|
|
281
|
+
EVM: EIP-712 typed data (pass to cdp evm accounts sign typed-data)
|
|
282
|
+
Solana: { "transaction": "<base64>" } (pass to cdp solana accounts sign transaction)
|
|
283
|
+
|
|
284
|
+
Examples:
|
|
285
|
+
cdp util x402 build --from 0xAddr --payment-requirements '[{"scheme":"exact","network":"eip155:8453","asset":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913","amount":"100000","payTo":"0xSeller","maxTimeoutSeconds":60,"extra":{"name":"USD Coin","version":"2"}}]'
|
|
286
|
+
`,Xs=`Encode payment payload as base64 header
|
|
287
|
+
|
|
288
|
+
Usage:
|
|
289
|
+
cdp util x402 encode --payment-requirements '<json>' --signature <sig> [--authorization '<json>'] [--x402-version N]
|
|
290
|
+
|
|
291
|
+
Flags:
|
|
292
|
+
--payment-requirements <json> Original payment requirements
|
|
293
|
+
--signature <sig> Signature from signing step
|
|
294
|
+
--authorization <json> Authorization data (EVM only, typed data message)
|
|
295
|
+
--x402-version <N> Protocol version (default: 1, use 2 for v2 servers)
|
|
296
|
+
|
|
297
|
+
Outputs base64 payment header value to stdout.
|
|
298
|
+
Use X-PAYMENT header for v1 servers, PAYMENT-SIGNATURE for v2.
|
|
299
|
+
`,zs=`Decode a base64 payment header
|
|
300
|
+
|
|
301
|
+
Usage:
|
|
302
|
+
cdp util x402 decode <base64-header>
|
|
303
|
+
echo '<base64>' | cdp util x402 decode
|
|
304
|
+
|
|
305
|
+
Outputs JSON payment payload to stdout.
|
|
306
|
+
`;async function Zs(t){if(t.length===0||t[0]==="-h"||t[0]==="--help"){process.stderr.write(Ks);return}let[e,...r]=t;if(e==="build")return Qs(r);if(e==="encode")return ei(r);if(e==="decode")return ti(r);throw new Error(`unknown x402 command: ${e}
|
|
307
|
+
Run: cdp util x402 --help`)}async function Qs(t){let e=L(t,[["from",null,!0],["payment-requirements",null,!0],["amount",null,!0]]);if(e.help){process.stderr.write(Ys);return}let r=e.flags.from;if(!r)throw new Error(`--from is required
|
|
308
|
+
Run: cdp util x402 build --help`);let n=e.flags["payment-requirements"];if(!n){if(process.stdin.isTTY)throw new Error(`--payment-requirements is required (or pipe JSON via stdin)
|
|
309
|
+
Run: cdp util x402 build --help`);n=(await lt()).toString("utf-8").trim()}if(!n)throw new Error("empty payment requirements");let o=Gt(n);if(ve(o.network)){let s;if(o.scheme==="exact")s=Ft(o,r);else if(o.scheme==="upto")s=Wt(o,r,e.flags.amount);else throw new Error(`unsupported EVM scheme: ${o.scheme}`);process.stdout.write(JSON.stringify(s,null,2)+`
|
|
310
|
+
`);return}if(Ee(o.network)){let s=await Vt(o,r);process.stdout.write(JSON.stringify(s,null,2)+`
|
|
311
|
+
`);return}throw new Error(`unsupported network: ${o.network}. Expected eip155:* or solana:*`)}function ei(t){let e=L(t,[["payment-requirements",null,!0],["signature",null,!0],["authorization",null,!0],["x402-version",null,!0]]);if(e.help){process.stderr.write(Xs);return}let r=e.flags["payment-requirements"],n=e.flags.signature,o=e.flags.authorization;if(!r)throw new Error("--payment-requirements is required");if(!n)throw new Error("--signature is required");let s=Gt(r),a={};if(o)try{a=JSON.parse(o)}catch{throw new Error("--authorization must be valid JSON")}else if(ve(s.network))throw new Error("--authorization is required for EVM payments");let i=e.flags["x402-version"]?parseInt(e.flags["x402-version"],10):1;if(isNaN(i))throw new Error("--x402-version must be a number");let c=_n(s,a,n,i);process.stdout.write(On(c)+`
|
|
312
|
+
`)}async function ti(t){let e;if(t.length>0&&t[0]!=="-h"&&t[0]!=="--help")e=t[0];else if(t[0]==="-h"||t[0]==="--help"){process.stderr.write(zs);return}else{if(process.stdin.isTTY)throw new Error(`provide base64 header as argument or pipe via stdin
|
|
313
|
+
Run: cdp util x402 decode --help`);e=(await lt()).toString("utf-8").trim()}if(!e)throw new Error("empty input");let r=Cn(e);process.stdout.write(JSON.stringify(r,null,2)+`
|
|
314
|
+
`)}function ri(t){if(t.length===0||t[0]==="-h"||t[0]==="--help"){process.stderr.write(Js);return}let[e,...r]=t;if(xn(e)){let n=En(e,r);process.stdout.write(n+`
|
|
315
|
+
`)}else{let n=bn(e),o=vn(n,r);process.stdout.write(o+`
|
|
316
|
+
`)}}function ni(t){if(t.length===0||t[0]==="-h"||t[0]==="--help"){process.stderr.write(`Decode a raw transaction
|
|
257
317
|
|
|
258
318
|
Usage:
|
|
259
319
|
cdp util tx-decode <hex-or-base64>
|
|
260
320
|
|
|
261
321
|
Auto-detects EVM (0x-prefixed hex) vs Solana (base64).
|
|
262
|
-
`);return}let e=t[0];if(!e||e.trim()==="")throw new Error("missing transaction data");if(e.startsWith("0x")){if(!/^0x[0-9a-fA-F]+$/.test(e))throw new Error("invalid hex transaction data");if(e.length<10)throw new Error("transaction data too short")}else if(Buffer.from(e,"base64").length<100)throw new Error("transaction data too short (minimum ~100 bytes for a valid Solana transaction)")
|
|
263
|
-
`)}function
|
|
264
|
-
`);return}throw new Error("usage: cdp history [clear [env.action]]")}function
|
|
322
|
+
`);return}let e=t[0];if(!e||e.trim()==="")throw new Error("missing transaction data");if(e.startsWith("0x")){if(!/^0x[0-9a-fA-F]+$/.test(e))throw new Error("invalid hex transaction data");if(e.length<10)throw new Error("transaction data too short")}else{if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new Error("invalid base64 transaction data");if(Buffer.from(e,"base64").length<100)throw new Error("transaction data too short (minimum ~100 bytes for a valid Solana transaction)")}let r;e.startsWith("0x")?r=an(e):r=gn(e),process.stdout.write(JSON.stringify(r,null,2)+`
|
|
323
|
+
`)}function qn(t){let e=D();if(t.length===0)return oi(e);if(t[0]==="clear"){let r=t[1],n;if(r&&r.includes(".")){let o=r.indexOf(".");n=We(e,r.slice(0,o),r.slice(o+1))}else r?n=We(e,r):n=We(e);q(e),process.stderr.write(`Cleared ${n} history ${n===1?"entry":"entries"}.
|
|
324
|
+
`);return}throw new Error("usage: cdp history [clear [env.action]]")}function oi(t){let e=[];for(let[o,s]of Object.entries(t.history))for(let[a,i]of Object.entries(s))e.push({env:o,action:a,lastUsed:i.last_used,fields:Object.keys(i.values)});if(e.length===0){process.stderr.write(`No saved history.
|
|
265
325
|
`);return}e.sort((o,s)=>s.lastUsed.localeCompare(o.lastUsed));let r=Math.max(...e.map(o=>o.env.length))+2,n=Math.max(...e.map(o=>o.action.length))+2;for(let o of e){let s=o.lastUsed.slice(0,10);process.stdout.write(`${o.env.padEnd(r)}${o.action.padEnd(n)}${s} ${o.fields.join(", ")}
|
|
266
|
-
`)}}import{readFileSync as
|
|
267
|
-
`,{mode:384})}function
|
|
326
|
+
`)}}import{readFileSync as Fn,writeFileSync as si,mkdirSync as Wn,readdirSync as Hn,existsSync as ee,cpSync as ii,rmSync as ai}from"node:fs";import Ln,{join as J,resolve as Mn}from"node:path";import{fileURLToPath as ci}from"node:url";import{homedir as jn}from"node:os";import{createInterface as Un}from"node:readline";function Kt(){try{return JSON.parse(Fn(me(),"utf8"))}catch{return{}}}function Jt(t){let e=te();Wn(e,{recursive:!0,mode:448}),si(me(),JSON.stringify(t,null,2)+`
|
|
327
|
+
`,{mode:384})}function Vn(){let t=Ln.dirname(ci(import.meta.url));return Ln.join(t,"..","skills")}function li(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return{name:"",description:""};let r=e[1],n=r.match(/^name:\s*(.+)$/m),o=r.match(/^description:\s*(.+)$/m);return{name:(n?.[1]??"").trim(),description:(o?.[1]??"").trim()}}function Gn(t){let e=t??Vn();if(!ee(e))return[];let r=[];for(let n of Hn(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=J(e,n.name,"SKILL.md");if(!ee(o))continue;let s=Fn(o,"utf8"),a=li(s);r.push({name:a.name||n.name,description:a.description,dir:J(e,n.name)})}return r.sort((n,o)=>n.name.localeCompare(o.name))}function ui(t,e){if(!ee(t))return 0;Wn(e,{recursive:!0});let r=0;for(let n of Hn(t,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=J(t,n.name,"SKILL.md");if(!ee(o))continue;let s=J(e,n.name);ii(J(t,n.name),s,{recursive:!0,force:!0}),r++}return r}async function di(){let t=process.platform==="win32"?J(process.env.USERPROFILE??jn(),".claude","skills"):J(jn(),".claude","skills");process.stderr.write(`Where should skills be installed?
|
|
268
328
|
`),process.stderr.write(`Tip: Not sure where your agent looks for skills? Ask your agent.
|
|
269
329
|
|
|
270
330
|
`),process.stderr.write(` 1) ${t} User \u2014 available across all projects (Recommended)
|
|
271
331
|
`),process.stderr.write(` 2) Other Specify a custom path
|
|
272
332
|
|
|
273
|
-
`);let e=
|
|
274
|
-
`),t)}return
|
|
333
|
+
`);let e=Un({input:process.stdin,output:process.stderr}),r=await new Promise(n=>{e.question("? Skills directory [1]: ",o=>{e.close(),n(o.trim())})});if(!r||r==="1")return t;if(r==="2"){let n=Un({input:process.stdin,output:process.stderr}),o=await new Promise(s=>{n.question("? Path: ",a=>{n.close(),s(a.trim())})});return o?Mn(o):(process.stderr.write(`No path provided, using default.
|
|
334
|
+
`),t)}return Mn(r)}async function pi(t){let e=Kt(),r=t||e.settings?.skillsDir,n=!1;r||(process.stdin.isTTY||(process.stderr.write(`error: no skills directory configured.
|
|
275
335
|
Run: cdp skills add --dir <path>
|
|
276
|
-
`),process.exit(1)),r=await
|
|
336
|
+
`),process.exit(1)),r=await di(),n=!0),(!e.settings?.skillsDir||t&&e.settings.skillsDir!==r)&&(e.settings||(e.settings={}),e.settings.skillsDir=r,Jt(e));let o=Vn(),s=ui(o,r);process.stderr.write(`Installed ${s} skills to ${r}.
|
|
277
337
|
`),n&&process.stderr.write(`Skills will auto-update on future installs.
|
|
278
|
-
`)}function
|
|
338
|
+
`)}function fi(){let e=Kt().settings?.skillsDir,r=Gn();if(r.length===0){process.stderr.write(`No bundled skills found.
|
|
279
339
|
`);return}let n=Math.max(...r.map(o=>o.name.length),4);process.stderr.write(`${"Name".padEnd(n+2)}${"Installed".padEnd(12)}Description
|
|
280
340
|
`),process.stderr.write(`${"\u2500".repeat(n+2)}${"\u2500".repeat(12)}${"\u2500".repeat(40)}
|
|
281
|
-
`);for(let o of r){let a=e&&
|
|
341
|
+
`);for(let o of r){let a=e&&ee(J(e,o.name,"SKILL.md"))?"yes":"no";process.stderr.write(`${o.name.padEnd(n+2)}${a.padEnd(12)}${o.description}
|
|
282
342
|
`)}process.stderr.write(`
|
|
283
343
|
${r.length} skills available.`),e?process.stderr.write(` Installed to: ${e}`):process.stderr.write(" Run: cdp skills add"),process.stderr.write(`
|
|
284
|
-
`)}function
|
|
285
|
-
`);return}if(!
|
|
286
|
-
`),t.settings&&delete t.settings.skillsDir,
|
|
287
|
-
`);return}let r=
|
|
344
|
+
`)}function mi(){let t=Kt(),e=t.settings?.skillsDir;if(!e){process.stderr.write(`No skills directory configured. Nothing to remove.
|
|
345
|
+
`);return}if(!ee(e)){process.stderr.write(`Skills directory not found: ${e}
|
|
346
|
+
`),t.settings&&delete t.settings.skillsDir,Jt(t),process.stderr.write(`Cleared skillsDir from config.
|
|
347
|
+
`);return}let r=Gn(),n=0;for(let o of r){let s=J(e,o.name);ee(s)&&(ai(s,{recursive:!0,force:!0}),n++)}t.settings&&delete t.settings.skillsDir,Jt(t),process.stderr.write(`Removed ${n} skills from ${e}.
|
|
288
348
|
`),process.stderr.write(`Cleared skillsDir from config.
|
|
289
|
-
`)}async function
|
|
349
|
+
`)}async function Jn(t){let e=t[0];if(!e||e==="-h"||e==="--help"){process.stderr.write(`Manage CDP agent skills
|
|
290
350
|
|
|
291
351
|
Usage:
|
|
292
352
|
cdp skills add Install/update skills to your skills directory
|
|
@@ -294,47 +354,47 @@ Usage:
|
|
|
294
354
|
cdp skills list List available skills from this package
|
|
295
355
|
cdp skills remove Remove installed skills and clear config
|
|
296
356
|
|
|
297
|
-
`);return}let r,n=t.slice(1);for(let o=0;o<n.length;o++)if(n[o]==="--dir"&&n[o+1]){r=n[++o];break}else if(n[o].startsWith("--dir=")){r=n[o].slice(6);break}switch(e){case"add":await
|
|
357
|
+
`);return}let r,n=t.slice(1);for(let o=0;o<n.length;o++)if(n[o]==="--dir"&&n[o+1]){r=n[++o];break}else if(n[o].startsWith("--dir=")){r=n[o].slice(6);break}switch(e){case"add":await pi(r);break;case"list":fi();break;case"remove":mi();break;default:process.stderr.write(`error: unknown skills subcommand: ${e}
|
|
298
358
|
Run: cdp skills --help
|
|
299
|
-
`),process.exit(1)}}import{writeFileSync as
|
|
300
|
-
`);return}let
|
|
301
|
-
This action takes ${e.pathParams.length} positional arg(s): ${f||"(none)"}`)}let d=[...l
|
|
302
|
-
${p}`);try{return await
|
|
303
|
-
${p}`:f.message)}}async function
|
|
304
|
-
`)}}let
|
|
305
|
-
`);let
|
|
306
|
-
`),
|
|
307
|
-
`)}catch{process.stdout.write(new TextDecoder().decode(
|
|
308
|
-
`)}return}let{name:
|
|
309
|
-
Configure: cdp env ${
|
|
310
|
-
Generate one at: https://portal.cdp.coinbase.com/products/server-wallet/accounts`);let m=
|
|
311
|
-
`),a=[];for(let i=0;i<s.length;i++){a.push(s[i]);for(let[l
|
|
312
|
-
`)}function
|
|
359
|
+
`),process.exit(1)}}import{writeFileSync as hi,readFileSync as yi,unlinkSync as wi,mkdtempSync as xi}from"node:fs";import{tmpdir as bi}from"node:os";import{join as Yn}from"node:path";import{execSync as vi,execFileSync as Ei}from"node:child_process";import{createInterface as gi}from"node:readline/promises";async function Kn(t,e){if(!e&&!process.stdin.isTTY)throw new Error("interactive prompts require a TTY");let r=gi({input:e??process.stdin,output:process.stderr});try{let n={};for(let o of t){let s=o.description?` (${o.description})`:"",a=await r.question(`${o.name}${s}: `);if(o.required&&!a.trim())throw new Error(`${o.name} is required`);a.trim()&&(n[o.name]=a.trim())}return n}finally{r.close()}}var ut=null;function Ie(){if(ut)return ut;try{return ut=ae(B()),ut}catch{return[]}}async function Xn(t,e,r,n,o=[]){let s=Ie().find(f=>f.name===t);if(!s)throw new Error(`unknown resource: ${t}`);let a=B(),i=!!a.resolve(e.operation.requestBody);if(n.template){process.stdout.write((zn(e,a)??"{}")+`
|
|
360
|
+
`);return}let c=[],l=[];for(let f of r)c.length<e.pathParams.length&&!se(f)?c.push(f):l.push(f);if(c.length<e.pathParams.length)throw new Error(`missing required argument(s): ${e.pathParams.slice(c.length).join(", ")}`);let u=l.filter(f=>!se(f));if(u.length>0){let f=e.pathParams.map(g=>`<${g}>`).join(", ");throw new Error(`unexpected positional argument(s): ${u.join(", ")}
|
|
361
|
+
This action takes ${e.pathParams.length} positional arg(s): ${f||"(none)"}`)}let d=[...c,...l],p="";for(let f=0;f<e.pathParams.length;f++){let g=c[f].includes("=")?c[f].split("=")[0]:c[f];if(o.includes(g)){let h=s.actions.find(y=>y.name.endsWith(` ${g}`));if(h){let y=h.pathParams.map(m=>` <${m}>`).join("");p=`Did you mean: cdp ${t} ${h.name}${y}`;break}}}if(p&&l.length>0&&!i)throw new Error(`unexpected argument(s): ${l.join(" ")}
|
|
362
|
+
${p}`);try{return await Si(s,e,t,d,l,i,a,n)}catch(f){throw new Error(p?`${f.message}
|
|
363
|
+
${p}`:f.message)}}async function Si(t,e,r,n,o,s,a,i){let c=e.path.replace(/^\/v2/,"");for(let b=0;b<e.pathParams.length;b++){let I=n[b];if(!I||I.trim()==="")throw new Error(`missing required argument: <${e.pathParams[b]}>`);c=c.replace(`{${e.pathParams[b]}}`,I)}let l=$i(o,a,e.operation),u=Je(l),d=D(),p=ye(d,i.envFlag),f=`${t.name}.${e.name.replace(/ /g,"_")}`;if(s&&l.length>0){let b={};if(p){let I=vt(d,p,f);if(I)for(let[N,R]of Object.entries(I.values))b[N]=Et(R)}u.body=Ii(l,b)}else if(s&&o.length===0&&p){let b=vt(d,p,f);if(b&&Object.keys(b.values).length>0){for(let[I,N]of Object.entries(b.values))H(u.body,I,Et(N));process.stderr.write(`reusing saved values for ${p}:${f}
|
|
364
|
+
`)}}let g=Ke(u);if(i.edit&&s?g=Zn(g,e,a):s&&(!g||g.length===0)&&(g=await Ai(g,e,a,r)),i.dryRun){process.stderr.write(`would ${e.method} ${c}
|
|
365
|
+
`);let b=u.query.toString();if(b&&process.stderr.write(`query: ${b}
|
|
366
|
+
`),g)try{process.stdout.write(JSON.stringify(JSON.parse(new TextDecoder().decode(g)),null,2)+`
|
|
367
|
+
`)}catch{process.stdout.write(new TextDecoder().decode(g)+`
|
|
368
|
+
`)}return}let{name:h,env:y}=re(d,i.envFlag);if(a.requiresWalletAuth(e.operation)&&!y.wallet_secret)throw new Error(`This operation requires a wallet secret.
|
|
369
|
+
Configure: cdp env ${h} --wallet-secret <secret>
|
|
370
|
+
Generate one at: https://portal.cdp.coinbase.com/products/server-wallet/accounts`);let m=ne(W(y,h),c),v=u.query.toString();v&&(m+=(m.includes("?")?"&":"?")+v);let S=m;do{let b=await oe({method:e.method,url:S,body:g,headers:u.headers,keyId:y.key_id,keySecret:y.key_secret,walletSecret:y.wallet_secret});if(S===m&&b.status<400&&s&&g&&p&&cr(d))try{let N={};(function R(O,P){for(let[A,E]of Object.entries(P)){let _=O?`${O}.${A}`:A;typeof E=="object"&&E&&!Array.isArray(E)?R(_,E):N[_]=JSON.stringify(E)}})("",JSON.parse(new TextDecoder().decode(g))),lr(d,p,f,N),q(d)}catch{}if(Ot(b,i.jq),!i.paginate)break;let I=et(S,b.body);if(!I)break;S=I}while(!0)}function ki(t,e){let r=new Map;for(let n of e.flattenBodyParams(t.operation)){if(!n.oneOf||n.oneOf.length<=1)continue;let o=new Set(n.oneOf[0].fields.map(a=>a.name)),s=n.oneOf.slice(1).map(a=>({...a,fields:a.fields.filter(i=>!o.has(i.name))})).filter(a=>a.fields.length>0);s.length>0&&r.set(n.path,s)}return r}function zn(t,e){let r=ze(t,e);if(Object.keys(r).length===0)return null;let n=JSON.stringify(r,null,2),o=ki(t,e);if(o.size===0)return n;let s=n.split(`
|
|
371
|
+
`),a=[];for(let i=0;i<s.length;i++){a.push(s[i]);for(let[c,l]of o){let u=c.split(".").pop();if(Pi(s,i,u)){let p=(s[i].match(/^(\s*)/)?.[1]??"")+" ";for(let f of l)for(let g of f.fields)a.splice(a.length-1,0,`${p}// ${JSON.stringify(g.name)}: ${JSON.stringify(At(g))}`);o.delete(c);break}}}return a.join(`
|
|
372
|
+
`)}function Pi(t,e,r){let n=t[e].trim();if(n!=="}"&&n!=="},")return!1;let o=t[e].search(/\S/);for(let s=e-1;s>=0;s--){let a=t[s],i=a.search(/\S/);if(i===o&&a.trimStart().startsWith(`"${r}":`))return!0;if(i<o)return!1}return!1}function $i(t,e,r){let n=new Set(e.getParameters(r).filter(s=>s?.in==="query").map(s=>s.name));if(n.size===0)return t;let o=new Set(e.flattenBodyParams(r).filter(s=>!s.path.includes(".")).map(s=>s.path));return t.map(s=>{let a=s.indexOf("=");if(a<=0||s[a-1]===":"||s[a+1]==="=")return s;let i=s.slice(0,a);return n.has(i)&&!o.has(i)?`${i}==${s.slice(a+1)}`:s})}function Ri(t,e){let r=e.resolve(t.operation.requestBody),n=e.resolve(r?.content?.["application/json"]?.schema);return n?{properties:n.properties??{},required:n.required??[]}:null}async function Ai(t,e,r,n){let o=Ri(e,r);if(!o)return t;let s=o.required,a=o.properties;if(s.length===0)return new TextEncoder().encode("{}");let i=s.some(c=>{let u=r.resolve(a[c])?.type;return u==="array"||u==="object"});if(!process.stdin.isTTY){let c=s.map(l=>{let u=r.resolve(a[l]);return` ${l} ${u?.type||"string"} required`}).join(`
|
|
313
373
|
`);throw new Error(`this action requires a request body
|
|
314
374
|
|
|
315
375
|
Required fields:
|
|
316
|
-
${
|
|
376
|
+
${c}
|
|
317
377
|
|
|
318
378
|
Provide fields inline:
|
|
319
|
-
cdp ${n} ${e.name} ${s.map(
|
|
379
|
+
cdp ${n} ${e.name} ${s.map(l=>`${l}=<value>`).join(" ")}
|
|
320
380
|
|
|
321
381
|
Or use --template to see the full body shape:
|
|
322
382
|
cdp ${n} ${e.name} --template
|
|
323
|
-
`)}if(s.length<=3&&!i){let
|
|
324
|
-
`),
|
|
383
|
+
`)}if(s.length<=3&&!i){let c=s.map(u=>{let d=r.resolve(a[u]),p=d?.description?.replace(/\n/g," ");return{name:u,type:d?.type||"string",description:p?p.slice(0,60):void 0,required:!0}}),l=await Kn(c);return new TextEncoder().encode(JSON.stringify(l))}return process.stderr.write(`This action requires structured input. Opening editor with template.
|
|
384
|
+
`),Zn(t,e,r)}function Ti(){if(process.platform!=="win32")return"vi";try{return vi("where code",{stdio:"pipe"}),"code --wait"}catch{}return"notepad"}function Zn(t,e,r){if(!process.stdin.isTTY)throw new Error("--edit requires an interactive terminal. Use --template to get the request body, then pass fields as arguments.");let n=process.env.VISUAL??process.env.EDITOR??Ti();(n.trim()==="code"||n.trim().endsWith("/code"))&&(n+=" --wait");let o=!t||t.length===0?zn(e,r)??"{}":(()=>{try{return JSON.stringify(JSON.parse(new TextDecoder().decode(t)),null,2)}catch{return new TextDecoder().decode(t)}})(),s=Yn(xi(Yn(bi(),"cdp-")),"request.json");hi(s,o);try{let[a,...i]=n.split(/\s+/);Ei(a,[...i,s],{stdio:"inherit",env:Fe()});let c=_i(yi(s,"utf8"));return JSON.parse(c),new TextEncoder().encode(c)}catch(a){throw new Error(a.message?.includes("Unexpected")?`edited file is not valid JSON: ${a.message}`:`editor: ${a.message}`)}finally{try{wi(s)}catch{}}}function Ii(t,e={}){let r={};for(let[n,o]of Object.entries(e))H(r,n,o);for(let n of t){if(n.startsWith("@")||n==="-")continue;let o=n.indexOf("=");if(!(o<=0))if(n[o-1]===":")try{H(r,n.slice(0,o-1),JSON.parse(n.slice(o+1)))}catch{}else{if(n[o+1]==="=")continue;H(r,n.slice(0,o),n.slice(o+1))}}return r}function _i(t){let e=t.split(`
|
|
325
385
|
`),r=[];for(let n of e)n.trimStart().startsWith("//")||r.push(n);return r.join(`
|
|
326
|
-
`).replace(/,(\s*[}\]])/g,"$1")}function
|
|
386
|
+
`).replace(/,(\s*[}\]])/g,"$1")}function Qn(t,e){let r=B(),n=process.stderr;n.write(`${e.summary||e.name}${Y(e.audience)}
|
|
327
387
|
`);let o=e.operation?.description;o&&n.write(`
|
|
328
|
-
`+
|
|
388
|
+
`+Qe(o));let s=`cdp ${t} ${e.name}`;for(let y of e.pathParams)s+=` <${y}>`;n.write(`
|
|
329
389
|
Usage:
|
|
330
390
|
${s} [fields...]
|
|
331
|
-
`);let a=r.getParameters(e.operation),i=a.filter(
|
|
391
|
+
`);let a=r.getParameters(e.operation),i=a.filter(y=>y.in==="path");if(i.length>0){n.write(`
|
|
332
392
|
Arguments:
|
|
333
|
-
`);let
|
|
393
|
+
`);let y=Math.max(...i.map(m=>m.name.length));for(let m of i){let v=m.schema?.type||"string",S=m.required?" required":"",b=(m.description||m.schema?.description||"").replace(/\n/g," "),I=` <${m.name}>${" ".repeat(Math.max(1,y-m.name.length+2))}${v}${S} `;X(n,I,b)}}let c=r.flattenBodyParams(e.operation);if(c.length>0){n.write(`
|
|
334
394
|
Fields:
|
|
335
|
-
`);let
|
|
395
|
+
`);let y=Math.max(...c.map(m=>m.path.length));for(let m of c){let v=m.required?"required":"",S=" ".repeat(Math.max(1,y-m.path.length+2)),b=" ".repeat(Math.max(1,8-m.type.length)),I=v?" ":" ",N=m.type==="array"||m.type==="object"?" (use :=json)":"",R=Ze(we((m.description||"").replace(/\n/g," "))),O=R.match(/^(.*?)(\[[-a-z0-9]+(?:,\s*[-a-z0-9]+)+\])(.*)$/i),P,A=null;O?(P=O[1].trim(),A=O[2]):P=R;let E=` ${m.path}${S}${m.type}${b}${v}${I}`;X(n,E,P+N),A&&X(n," ".repeat(E.length),A)}}let l=a.filter(y=>y.in==="query");if(l.length>0){n.write(`
|
|
336
396
|
Query params (use == syntax):
|
|
337
|
-
`);let
|
|
397
|
+
`);let y=Math.max(...l.map(m=>m.name.length));for(let m of l){let v=m.schema?.type||"string",S=(m.description||m.schema?.description||"").replace(/\n/g," ");m.schema?.enum?.length&&(S+=(S?" ":"")+`[${m.schema.enum.join(", ")}]`);let b=` ${m.name}${" ".repeat(Math.max(1,y-m.name.length+2))}${v} `;X(n,b,S)}}let u=c.length>0,d=r.getResponseInfo(e.operation),p=d&&d.fields.includes("nextPageToken");if(n.write(`
|
|
338
398
|
Flags:
|
|
339
399
|
`),u&&n.write(` --template Show request body template from spec
|
|
340
400
|
`),n.write(` --dry-run Preview request without sending
|
|
@@ -343,15 +403,15 @@ Flags:
|
|
|
343
403
|
`),p&&n.write(` --paginate Auto-paginate using nextPageToken
|
|
344
404
|
`),d&&d.fieldDetails.length>0){n.write(`
|
|
345
405
|
Response:
|
|
346
|
-
`);let
|
|
406
|
+
`);let y=Math.max(...d.fieldDetails.map(m=>m.name.length));for(let m of d.fieldDetails){let v=` ${m.name.padEnd(y+2)}${m.type.padEnd(8)}`;X(n,v,m.description)}}let f=ze(e,r),g=f&&Object.keys(f).length>0,h=l.length>0;if(g||h){if(n.write(`
|
|
347
407
|
Example:
|
|
348
|
-
`+s),
|
|
349
|
-
`)}}function
|
|
408
|
+
`+s),g)for(let[y,m]of Object.entries(f))typeof m=="string"&&!m.startsWith("<")?n.write(` ${y}=${m}`):typeof m=="object"&&n.write(` '${y}:=${JSON.stringify(m)}'`);if(h)for(let y of l){let m=y.schema?.example||y.schema?.default||`<${y.name}>`;n.write(` ${y.name}==${m}`)}n.write(`
|
|
409
|
+
`)}}function eo(t){let e=Ie().find(r=>r.name===t);e||(process.stderr.write(`error: unknown resource: ${t}
|
|
350
410
|
Run: cdp api
|
|
351
411
|
`),process.exit(1)),process.stderr.write(`Manage ${e.name}
|
|
352
412
|
|
|
353
413
|
Available actions:
|
|
354
|
-
`);for(let r of e.actions){let n=r.pathParams.map(o=>` <${o}>`).join("");process.stderr.write(` cdp ${e.name} ${r.name}${n} ${r.summary}${
|
|
414
|
+
`);for(let r of e.actions){let n=r.pathParams.map(o=>` <${o}>`).join("");process.stderr.write(` cdp ${e.name} ${r.name}${n} ${r.summary}${Y(r.audience)}
|
|
355
415
|
`)}process.stderr.write(`
|
|
356
416
|
Flags:
|
|
357
417
|
--template Show request body template from spec
|
|
@@ -359,28 +419,28 @@ Flags:
|
|
|
359
419
|
--edit Open request body in $EDITOR
|
|
360
420
|
--jq <expr> jq filter expression for response
|
|
361
421
|
--paginate Auto-paginate using nextPageToken
|
|
362
|
-
`)}var
|
|
422
|
+
`)}var _e=class extends Error{constructor(e){super(e),this.name="HelpExit"}};function to(t){let e={children:new Map};for(let r of t){let n=e;for(let o of r.name.split(" "))n.children.has(o)||n.children.set(o,{children:new Map}),n=n.children.get(o);n.action=r}return e}function ro(t,e,r){let n=t,o,s=0,a=[],i=[];for(let d=0;d<e.length;d++){let p=e[d],f=n.children.get(p);if(f){i.push(p),a=[...n.children.keys()],n=f,n.action&&(o=n.action,s=i.length);continue}if(p.includes("=")){let g=p.split("=")[0],h=n.children.get(g);if(h?.action){let y=h.action.pathParams.map(v=>` <${v}>`).join(""),m=i.length>0?`cdp ${r} ${i.join(" ")}`:`cdp ${r}`;throw new Error(`Did you mean: ${m} ${h.action.name.split(" ").pop()}${y}`)}}break}if(o)return{action:o,remaining:e.slice(s),siblingNames:a};let c=e[i.length],l=i.length>0?`cdp ${r} ${i.join(" ")}`:`cdp ${r}`,u=Oi(n,r);throw c&&c!=="--help"&&c!=="-h"?new Error(`unknown subcommand "${c}" for ${l}
|
|
363
423
|
|
|
364
424
|
Available actions:
|
|
365
|
-
${u}`):new
|
|
425
|
+
${u}`):new _e(`${l}
|
|
366
426
|
|
|
367
427
|
Available actions:
|
|
368
|
-
${u}`)}function
|
|
369
|
-
`)}process.stdout.on("error",t=>{throw t.code==="EPIPE"&&process.exit(0),t});process.stderr.on("error",t=>{throw t.code==="EPIPE"&&process.exit(0),t});var[
|
|
370
|
-
`),process.exit(1));try{let t=
|
|
428
|
+
${u}`)}function Oi(t,e){let r=[];function n(o){if(o.action){let s=o.action.pathParams.map(a=>` <${a}>`).join("");r.push(` cdp ${e} ${o.action.name}${s}`)}for(let s of o.children.values())n(s)}return n(t),r.join(`
|
|
429
|
+
`)}process.stdout.on("error",t=>{throw t.code==="EPIPE"&&process.exit(0),t});process.stderr.on("error",t=>{throw t.code==="EPIPE"&&process.exit(0),t});var[qi]=process.versions.node.split(".").map(Number);qi<22&&(process.stderr.write(`cdp requires Node.js ${22}+. You have: ${process.versions.node}
|
|
430
|
+
`),process.exit(1));try{let t=Ni(Bi(Di(import.meta.url)),nr);Qt(JSON.parse(Ci(t,"utf8")))}catch{}function Li(){let t=Ie(),r=B().groups();return`CLI for the Coinbase Developer Platform API
|
|
371
431
|
|
|
372
432
|
Usage:
|
|
373
433
|
cdp <resource> [action] [fields...]
|
|
374
434
|
cdp <command> [args...]
|
|
375
435
|
|
|
376
436
|
Resources:
|
|
377
|
-
${t.map(o=>{let s=r.find(i=>i.name===o.name),a=s&&
|
|
437
|
+
${t.map(o=>{let s=r.find(i=>i.name===o.name),a=s&&Oe(s)||o.name;return` ${o.name.padEnd(30)}${a} (${o.actions.length} actions)`}).join(`
|
|
378
438
|
`)}
|
|
379
439
|
|
|
380
440
|
Commands:
|
|
381
441
|
env [name] Manage environments and API keys
|
|
382
442
|
api [path] [fields...] Raw API access / browse endpoints
|
|
383
|
-
util <command> Client-side utilities (tx-encode, tx-decode, abi-encode, encrypt-key)
|
|
443
|
+
util <command> Client-side utilities (tx-encode, tx-decode, abi-encode, encrypt-key, x402)
|
|
384
444
|
skills <command> Manage agent skills (add, list, remove)
|
|
385
445
|
history [clear] View or clear saved request history
|
|
386
446
|
mcp MCP server (invoked by AI agents)
|
|
@@ -389,8 +449,8 @@ Global Flags:
|
|
|
389
449
|
-e, --env <name> Environment to use (overrides default)
|
|
390
450
|
-V, --version Show version
|
|
391
451
|
-h, --help Show help
|
|
392
|
-
`}async function
|
|
393
|
-
`);return}if(
|
|
452
|
+
`}async function Mi(){let t=process.argv.slice(2),e="",r=[];for(let s=0;s<t.length;s++){let a=t[s];a==="-e"||a==="--env"?e=t[++s]??"":a.startsWith("--env=")?e=a.slice(6):a.startsWith("-e")&&a.length>2?e=a.slice(2):r.push(a)}if(r[0]==="--version"||r[0]==="-V"){process.stdout.write(`cdp ${V}
|
|
453
|
+
`);return}if(Yt=gr(),r.length===0||r[0]==="-h"||r[0]==="--help"||r[0]==="help"){process.stderr.write(Li());return}let[n,...o]=r;if(n==="env"){let s=L(o,[["key-id",null,!0],["key-secret",null,!0],["key-file","k",!0],["url",null,!0],["remove",null,!1],["wallet-secret",null,!0],["wallet-secret-file","w",!0],["remove-wallet-secret",null,!1],["plaintext",null,!1]]);if(s.help){process.stderr.write(`Manage environments and API keys
|
|
394
454
|
|
|
395
455
|
Usage:
|
|
396
456
|
cdp env List all environments
|
|
@@ -410,14 +470,14 @@ Flags:
|
|
|
410
470
|
-w, --wallet-secret-file <f> Import wallet secret from file
|
|
411
471
|
--remove-wallet-secret Remove wallet secret only
|
|
412
472
|
--plaintext Store secrets in config file instead of OS keyring
|
|
413
|
-
`);return}await
|
|
473
|
+
`);return}await Sr(s.args,{keyId:s.flags["key-id"],keySecret:s.flags["key-secret"],keyFile:s.flags["key-file"],url:s.flags.url,remove:!!s.flags.remove,walletSecret:s.flags["wallet-secret"],walletSecretFile:s.flags["wallet-secret-file"],removeWalletSecret:!!s.flags["remove-wallet-secret"],plaintext:!!s.flags.plaintext,envFlag:e})}else if(n==="api")await Ur(o,{envFlag:e});else if(n==="history"){let s=L(o,[]);if(s.help){process.stderr.write(`View or clear saved request history
|
|
414
474
|
|
|
415
475
|
Usage:
|
|
416
476
|
cdp history Show all saved history
|
|
417
477
|
cdp history clear Clear all history
|
|
418
478
|
cdp history clear <env> Clear history for an environment
|
|
419
479
|
cdp history clear <env>.<action> Clear a specific entry
|
|
420
|
-
`);return}
|
|
480
|
+
`);return}qn(s.args)}else if(n==="util")await Dn(o);else if(n==="skills"){await Jn(o);return}else if(n==="mcp"){if(L(o,[]).help){process.stderr.write(`MCP server for AI agent integration
|
|
421
481
|
|
|
422
482
|
Usage:
|
|
423
483
|
cdp mcp Start MCP server over stdio
|
|
@@ -425,8 +485,8 @@ Usage:
|
|
|
425
485
|
The MCP server implements the Model Context Protocol (JSON-RPC over
|
|
426
486
|
stdin/stdout) and exposes all CDP API resources as tools. It is
|
|
427
487
|
typically invoked automatically by AI agents, not run directly.
|
|
428
|
-
`);return}
|
|
488
|
+
`);return}Gr();return}else{let s=Ie().find(l=>l.name===n);if(s||(process.stderr.write(`error: unknown command "${n}"
|
|
429
489
|
Run: cdp --help
|
|
430
|
-
`),process.exit(1)),o.length===0||o[0]==="-h"||o[0]==="--help"){
|
|
490
|
+
`),process.exit(1)),o.length===0||o[0]==="-h"||o[0]==="--help"){eo(n);return}let a=to(s.actions),i=ro(a,o,n),c=L(i.remaining,[["template",null,!1],["dry-run",null,!1],["edit",null,!1],["jq",null,!0],["paginate",null,!1]]);if(c.help){Qn(n,i.action);return}await Xn(n,i.action,c.args,{template:!!c.flags.template,dryRun:!!c.flags["dry-run"],edit:!!c.flags.edit,paginate:!!c.flags.paginate,jq:c.flags.jq,envFlag:e},i.siblingNames)}}var Yt;Mi().catch(t=>{t instanceof _e&&(process.stderr.write(t.message+`
|
|
431
491
|
`),process.exit(0)),process.stderr.write(`error: ${t.message}
|
|
432
|
-
`),process.exit(1)}).finally(async()=>{if(!
|
|
492
|
+
`),process.exit(1)}).finally(async()=>{if(!Yt||!process.stderr.isTTY)return;let t=await Yt.catch(()=>"");t&&process.stderr.write(t)});
|