@coinbase/cdp-cli 0.0.0 → 2.0.1

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 ADDED
@@ -0,0 +1,432 @@
1
+ #!/usr/bin/env node
2
+ var h={live:"https://api.cdp.coinbase.com/platform/v2"};var y={production:"live"};import{readFileSync as Gs}from"node:fs";import{dirname as Ks,join as Js}from"node:path";import{fileURLToPath as Ys}from"node:url";function Te(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 Mn=["get","post","put","patch","delete"],Nt={POST:0,GET:1,PUT:2,PATCH:3,DELETE:4};function Dt(t,e){return t.path===e.path?(Nt[t.method]??5)-(Nt[e.method]??5):t.path<e.path?-1:1}var nt=class{doc;constructor(e){this.doc=e}allEndpoints(){let e=[];for(let[r,n]of Object.entries(this.doc.paths??{}))for(let o of Mn){let s=n[o];if(!s)continue;let a=this.resolve(s);a?.parameters&&(a.parameters=a.parameters.map(l=>{let c=this.resolve(l);return c?.schema&&(c.schema=this.resolve(c.schema)),c})),!(a?.security??[]).some(l=>l&&typeof l=="object"&&"endUserAuth"in l)&&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(Dt),{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(Dt)}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 l=this.resolve(i);l?.properties&&Object.assign(a.properties,l.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 l=this.resolve(i),c=l?.type??"object";if(Array.isArray(c)&&(c=c[0]??"string"),c==="array"&&l?.items){let u=this.resolve(l.items);if(u?.properties){let d=Object.keys(u.properties).join(", ");s.push({name:a,type:"array",description:(l.description??"")+` {${d}}`});continue}}s.push({name:a,type:c,description:(l?.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 l=e?`${e}.${a}`:a;if(i.type==="object"&&i.properties){this.flattenSchema(l,i,i.required??[],o);continue}let c;i.oneOf&&(c=i.oneOf.map(p=>{let f=this.resolve(p);if(!f)return null;if(f.allOf){let g={...f,properties:{},required:[]};for(let m of f.allOf.map(E=>this.resolve(E)).filter(Boolean))m.properties&&Object.assign(g.properties,m.properties),m.required&&g.required.push(...m.required);f=g}if(!f.properties||Object.keys(f.properties).length===0)return null;let w=new Set(f.required??[]),S=f.example??{};return{title:p.title??f.title??"",fields:Object.entries(f.properties).map(([g,m])=>{let E=this.resolve(m),b=E?.type??(E?.allOf?this.resolve(E.allOf[0])?.type??"string":"string");return Array.isArray(b)&&(b=b[0]??"string"),{name:g,type:b,required:w.has(g),description:E?.description??"",example:E?.example??S[g]??null}})}}).filter(Boolean),c.length===0&&(c=void 0));let u=i.type??(c?"object":"string");Array.isArray(u)&&(u=u[0]??"string");let d=i.description??"";if(i.enum?.length&&(d+=(d?" ":"")+`[${i.enum.join(", ")}]`),c){let p=c.map(f=>f.title).filter(Boolean);p.length>0&&(d+=(d?" ":"")+`(one of: ${p.join(", ")})`)}o.push({path:l,type:u,required:s.has(a),description:d,default_:i.default??null,example:i.example??null,oneOf:c})}}},ot=null;function qt(t){ot=new nt(t)}function B(){if(!ot)throw new Error("spec not initialized");return ot}function st(t){return(t.match(/\{([^}]+)\}/g)??[]).map(e=>e.slice(1,-1))}function it(t,e){let r=st(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 We}from"node:readline/promises";import{readFileSync as er}from"node:fs";import{readFileSync as Wn,writeFileSync as Hn,mkdirSync as Vn}from"node:fs";import{homedir as Ht}from"node:os";import{join as je}from"node:path";var Lt="@coinbase/cdp-cli",_e="https://registry.npmjs.org",jt=typeof h<"u"?h:{live:"https://api.cdp.coinbase.com/platform/v2"},Mt=typeof y<"u"?y:{production:"live"},Ut="spec.json";import{execFileSync as Ce}from"node:child_process";var Oe="/usr/bin/security",Be=class{constructor(){try{Ce(Oe,["list-keychains"],{stdio:["pipe","pipe","pipe"]})}catch{throw new Error("Keychain not accessible")}}get(e,r){try{return Ce(Oe,["find-generic-password","-s",e,"-a",r,"-w"],{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trimEnd()}catch{return null}}set(e,r,n){Ce(Oe,["add-generic-password","-U","-s",e,"-a",r,"-w",n],{stdio:["pipe","pipe","pipe"]})}delete(e,r){try{Ce(Oe,["delete-generic-password","-s",e,"-a",r],{stdio:["pipe","pipe","pipe"]})}catch{}}};import{execFileSync as Ne}from"node:child_process";var De=class{constructor(){try{Ne("which",["secret-tool"],{stdio:["pipe","pipe","pipe"]})}catch{throw new Error("secret-tool not found")}}get(e,r){try{return Ne("secret-tool",["lookup","service",e,"account",r],{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trimEnd()}catch{return null}}set(e,r,n){Ne("secret-tool",["store","--label",`${e}:${r}`,"service",e,"account",r],{input:n,stdio:["pipe","pipe","pipe"]})}delete(e,r){try{Ne("secret-tool",["clear","service",e,"account",r],{stdio:["pipe","pipe","pipe"]})}catch{}}};import{execFileSync as Un}from"node:child_process";function at(t,e){return`${t}:${e}`}function fe(t){return t.replace(/'/g,"''")}var Fn=`
3
+ if (-not ([System.Management.Automation.PSTypeName]'Win32.Cred').Type) {
4
+ Add-Type -Namespace Win32 -Name Cred -MemberDefinition '
5
+ [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
6
+ public static extern bool CredWrite(ref CREDENTIAL cred, int flags);
7
+ [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
8
+ public static extern bool CredRead(string target, int type, int flags, out IntPtr cred);
9
+ [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
10
+ public static extern bool CredDelete(string target, int type, int flags);
11
+ [DllImport("advapi32.dll")] public static extern void CredFree(IntPtr cred);
12
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
13
+ public struct CREDENTIAL {
14
+ public int Flags; public int Type; public string TargetName; public string Comment;
15
+ public long LastWritten; public int CredentialBlobSize; public IntPtr CredentialBlob;
16
+ public int Persist; public int AttributeCount; public IntPtr Attributes;
17
+ public string TargetAlias; public string UserName;
18
+ }'
19
+ }
20
+ `;function ct(t){let e=Fn+t,r=Buffer.from(e,"utf16le").toString("base64");return Un("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",r],{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trimEnd()}var qe=class{get(e,r){try{let n=fe(at(e,r));return ct(`
21
+ $ptr = [IntPtr]::Zero
22
+ if ([Win32.Cred]::CredRead('${n}', 1, 0, [ref]$ptr)) {
23
+ $cred = [Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [Type][Win32.Cred+CREDENTIAL])
24
+ $bytes = [byte[]]::new($cred.CredentialBlobSize)
25
+ [Runtime.InteropServices.Marshal]::Copy($cred.CredentialBlob, $bytes, 0, $cred.CredentialBlobSize)
26
+ [Win32.Cred]::CredFree($ptr)
27
+ [Text.Encoding]::Unicode.GetString($bytes)
28
+ }`)||null}catch{return null}}set(e,r,n){let o=fe(at(e,r)),s=fe(r),a=fe(n);ct(`
29
+ $bytes = [Text.Encoding]::Unicode.GetBytes('${a}')
30
+ $blob = [Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length)
31
+ [Runtime.InteropServices.Marshal]::Copy($bytes, 0, $blob, $bytes.Length)
32
+ $cred = New-Object Win32.Cred+CREDENTIAL
33
+ $cred.Type = 1
34
+ $cred.TargetName = '${o}'
35
+ $cred.UserName = '${s}'
36
+ $cred.CredentialBlobSize = $bytes.Length
37
+ $cred.CredentialBlob = $blob
38
+ $cred.Persist = 2
39
+ if (-not [Win32.Cred]::CredWrite([ref]$cred, 0)) {
40
+ throw "CredWrite failed: $([Runtime.InteropServices.Marshal]::GetLastWin32Error())"
41
+ }
42
+ [Runtime.InteropServices.Marshal]::FreeHGlobal($blob)`)}delete(e,r){try{ct(`[void][Win32.Cred]::CredDelete('${fe(at(e,r))}', 1, 0)`)}catch{}}};var lt="cdp-cli",Y,Ft=!1;function Le(){if(Y!==void 0)return Y;try{process.platform==="darwin"?Y=new Be:process.platform==="linux"?Y=new De:process.platform==="win32"?Y=new qe:Y=null}catch{Ft||(process.stderr.write(`warning: OS keychain not accessible \u2014 secrets stored in keychain will not be available
43
+ `),Ft=!0),Y=null}return Y}function re(t){let e=Le();if(!e)return null;try{return e.get(lt,t)}catch{return null}}function me(t,e){let r=Le();if(!r)return!1;try{return r.set(lt,t,e),!0}catch{return!1}}function ge(t){let e=Le();if(e)try{e.delete(lt,t)}catch{}}function Wt(){return Le()!==null}var F=jt,Vt=Mt;function se(){if(process.env.CDP_CONFIG_DIR)return process.env.CDP_CONFIG_DIR;if(process.platform==="win32"){let t=process.env.APPDATA??je(Ht(),"AppData","Roaming");return je(t,"cdp")}return je(Ht(),".config","cdp")}function he(){return je(se(),"config.json")}function W(t,e){if(t.url)return t.url;if(F[e])return F[e];let r=Vt[e];if(r&&F[r])return F[r];let n={...F};for(let[s,a]of Object.entries(Vt))F[a]&&(n[s]=F[a]);let o=Object.keys(n).find(s=>e.startsWith(s+"-"));return o?n[o]:""}function ye(t){return Object.values(F).some(e=>t.startsWith(e.replace(/\/platform\/v2$/,"")))}function D(){let t={env:"",environments:{},history:{}},e=he();try{let r=Wn(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=se();Vn(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),Hn(he(),JSON.stringify(r,null,2)+`
44
+ `,{mode:384})}function we(t){return re(`${t}:wallet`)}function ut(t,e){return me(`${t}:wallet`,e)}function dt(t){ge(`${t}:wallet`)}function xe(t,e){return e||process.env.CDP_ENV||t.env}function ie(t,e){let r=xe(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=re(r);s&&(n.key_secret=s)}if(!n.wallet_secret){let s=we(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,ye(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 Gn=["CDP_KEY_SECRET","CDP_KEY_ID","CDP_WALLET_SECRET"];function Me(){let t={...process.env};for(let e of Gn)delete t[e];return t}function Gt(t){return process.env.CDP_NO_HISTORY?!1:t.settings?.history?.enabled!==!1}function pt(t,e,r){return t.history[e]?.[r]}function ft(t){try{return JSON.parse(t)}catch{return t}}function Kt(t,e,r,n){t.history[e]||(t.history[e]={}),t.history[e][r]={last_used:new Date().toISOString(),values:n}}function Ue(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 Yt,createPrivateKey as Kn,createHash as Jn,sign as Yn,randomBytes as zn}from"node:crypto";function gt(t){return Buffer.from(t).toString("base64url")}function Fe(t){return gt(Buffer.from(JSON.stringify(t)))}function zt(){return zn(16).toString("hex")}function Xn(t){return t.includes("-----BEGIN EC PRIVATE KEY-----")}function Qn(t){try{return Buffer.from(t,"base64").length===64}catch{return!1}}function Zn(t,e,r,n,o){let s=Math.floor(Date.now()/1e3),a=zt(),i={sub:t,iss:"cdp",nbf:s,iat:s,exp:s+120},l=`${r} ${n}${o}`;if(r&&n&&o&&(i.uris=[l]),Xn(e))return eo(t,e,i,a);if(Qn(e))return to(t,e,i,a);throw new Error("invalid key format - must be either PEM EC key or base64 Ed25519 key")}function Xt(t,e,r){let n=`${Fe(t)}.${Fe(e)}`,o=Yt("SHA256");o.update(n);let s=o.sign(r);return`${n}.${gt(ro(s))}`}function eo(t,e,r,n){return Xt({alg:"ES256",typ:"JWT",kid:t,nonce:n},r,e)}function to(t,e,r,n){let s=`${Fe({alg:"EdDSA",typ:"JWT",kid:t,nonce:n})}.${Fe(r)}`,a=Buffer.from(e,"base64"),i=Kn({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),a.subarray(0,32)]),format:"der",type:"pkcs8"}),l=Yn(null,Buffer.from(s),i);return`${s}.${gt(l)}`}function ro(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=Jt(n,32),s=Jt(s,32),Buffer.concat([n,s])}function Jt(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 no(t,e,r,n,o){let s=Math.floor(Date.now()/1e3),a=zt(),l={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=mt(u);l.reqHash=Jn("sha256").update(JSON.stringify(d)).digest("hex")}}catch{}let c=Qt(t);return Xt({alg:"ES256",typ:"JWT"},l,c)}function Qt(t){return`-----BEGIN PRIVATE KEY-----
46
+ ${Buffer.from(t,"base64").toString("base64").match(/.{1,64}/g)?.join(`
47
+ `)}
48
+ -----END PRIVATE KEY-----`}function ht(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=Qt(t);try{Yt("SHA256").sign(r)}catch{throw new Error("wallet secret is not a valid EC private key")}}function mt(t){return Array.isArray(t)?t.map(mt):typeof t!="object"||t===null?t:Object.keys(t).sort().reduce((e,r)=>(e[r]=mt(t[r]),e),{})}function ae(t,e){e.startsWith("/")||(e="/"+e);let r=new URL(t);return r.pathname=r.pathname.replace(/\/$/,"")+e,r.toString()}async function ce(t){let e=new URL(t.url),n={Authorization:`Bearer ${Zn(t.keyId,t.keySecret,t.method,e.host,e.pathname)}`,"Content-Type":"application/json",...t.headers};t.walletSecret&&(n["X-Wallet-Auth"]=no(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 tr(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>
49
+ `);return}let l=Math.max(14,...i.map(c=>c.length));for(let c of i){let u=r.environments[c]??{},d=W(u,c),p=u.key_id?u.key_id.length>40?u.key_id.slice(0,37)+"...":u.key_id:"(no key)",f=we(c)?" (wallet)":"";process.stdout.write(`${c===r.env?"* ":" "}${c.padEnd(l)} ${(d.length>45?d.slice(0,42)+"...":d).padEnd(45)} ${p}${f}
50
+ `)}return}let n=t[0];if(e.remove){ge(n),dt(n),delete r.environments[n],r.env===n&&(r.env=""),q(r),process.stderr.write(`Removed ${n}.
51
+ `);return}if(e.removeWalletSecret){dt(n),process.stderr.write(`Removed wallet secret for ${n}.
52
+ `);return}let o=r.environments[n]??{},s=e.walletSecret??(e.walletSecretFile?oo(e.walletSecretFile):void 0);if(s){if(!o.key_id&&!re(n))throw new Error(`environment "${n}" has no API key. Configure one first: cdp env ${n} --key-file <file>`);ht(s);let i=!!we(n);ut(n,s),process.stderr.write(`Wallet secret ${i?"updated":"saved"} for ${n}.
53
+ `);return}if(e.keyFile){let i=so(e.keyFile);o.key_id=i.keyId,o.key_secret=i.keySecret,e.url&&(o.url=e.url,ye(e.url)||process.stderr.write(`warning: custom URL does not match a known CDP endpoint
54
+ `)),yt(n,o,e.plaintext),r.environments[n]=o,r.env=n,q(r),process.stderr.write(`Loaded key from ${e.keyFile}. Switched to ${n}.
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,ye(e.url)||process.stderr.write(`warning: custom URL does not match a known CDP endpoint
56
+ `)),yt(n,o,e.plaintext),r.environments[n]=o,r.env=n,q(r),process.stderr.write(`Saved and switched to ${n}.
57
+ `);return}if(o.key_id&&(o.key_secret||re(n))){r.env=n,q(r),process.stderr.write(`Switched to ${n}.
58
+ `);return}if(!process.stdout.isTTY)throw new Error(`environment "${n}" needs API keys. Run: cdp env ${n} --key-id=... --key-secret=...`);let a=We({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 Zt("API Key Secret: ");if(!i.trim())throw new Error("API Key Secret is required");o.key_secret=i.trim(),a=We({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(),ye(o.url)||process.stderr.write(`warning: custom URL does not match a known CDP endpoint
59
+ `))}if(!o.wallet_secret&&!we(n)){a.close();let i=await Zt("Wallet Secret (optional, press Enter to skip): ");i.trim()&&(ht(i.trim()),o.wallet_secret=i.trim()),a=We({input:process.stdin,output:process.stderr})}}finally{a.close()}yt(n,o),r.environments[n]=o,r.env=n,q(r),process.stderr.write(`Saved. Switched to ${n}.
60
+ `)}function yt(t,e,r){if(!r&&(e.key_secret||e.wallet_secret)){if(!Wt()){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.
61
+ ${n}use --plaintext to store in config file.`)}e.key_secret&&me(t,e.key_secret)&&delete e.key_secret,e.wallet_secret&&ut(t,e.wallet_secret)&&delete e.wallet_secret}}function Zt(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
+ `||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=We({input:process.stdin});r.once("line",n=>{r.close(),e(n)})})}function oo(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 so(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 io,openSync as ao,readSync as co,closeSync as lo}from"node:fs";var uo={readFile(t){try{return io(t)}catch(e){throw new Error(`reading file ${t}: ${e.message}`)}},readStdin(){let t=[],e=Buffer.alloc(65536),r;try{r=ao("/dev/stdin","r")}catch{throw new Error("reading stdin: cannot open")}try{let n;for(;(n=co(r,e))>0;)t.push(Buffer.from(e.subarray(0,n)))}catch{}return lo(r),Buffer.concat(t)}};function He(t,e=uo){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(po(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 po(t){let e=t.indexOf(":");return e<=0||t.slice(0,e).includes("=")?!1:t[0]>="A"&&t[0]<="Z"}function rr(t){return Object.keys(t.body).length>0||t.rawBody!==null}function Ve(t){return t.rawBody?t.rawBody:Object.keys(t.body).length===0?null:new TextEncoder().encode(JSON.stringify(t.body))}var fo=new Set(["__proto__","constructor","prototype"]);function le(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(fo.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 mo}from"node:child_process";function nr(t,e){try{return mo("jq",["-r",e],{input:t,encoding:"utf8",maxBuffer:10*1024*1024,env:Me()}).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 or(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 sr(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 ir(t){return t.children.size>0||t.param!==null}function Ge(t){let e=[...t.endpoints];for(let r of t.children.values())e.push(...Ge(r));return t.param&&e.push(...Ge(t.param.node)),e}function Ke(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(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}function z(t){return t&&t!=="public"?` [${t}]`:""}function ar(t,e){return`cdp_${t.replace(/-/g,"_")}_${e.replace(/[-\s]/g,"_")}`}function go(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 ho(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,l]of Object.entries(s.properties)){let c=e.resolve(l),u={type:c.type??"string"};if(c.description){let d=c.description.replace(/\n/g," ");u.description=d.length>80?d.slice(0,77)+"...":d}c.enum&&(u.enum=c.enum),c.example!=null&&(u.example=c.example),r[i]=u,a.has(i)&&n.push(i)}}function cr(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);ho(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:ar(n.name,o.name),description:`${o.method} ${o.path}${o.summary?" \u2014 "+o.summary:""}${go(o,t)}${z(o.audience)}`,inputSchema:{type:"object",properties:s,required:a.length>0?a:void 0}})}return r}function lr(t,e,r){let n=t.path.replace(/^\/v2/,"");for(let l of t.pathParams){if(!e[l])return T(`Missing required parameter: ${l}`,!0);n=n.replace(`{${l}}`,e[l])}let o=new Set(t.pathParams),s=new Set,a=new URLSearchParams;for(let l of r.getParameters(t.operation))l?.in==="query"&&(s.add(l.name),e[l.name]!=null&&a.set(l.name,String(e[l.name])));let i=null;if(e.body&&typeof e.body=="object")i=new TextEncoder().encode(JSON.stringify(e.body));else{let l={};for(let[c,u]of Object.entries(e))!o.has(c)&&!s.has(c)&&(l[c]=u);Object.keys(l).length>0&&(i=new TextEncoder().encode(JSON.stringify(l)))}return{method:t.method,urlPath:n,queryParams:a,body:i}}function ur(t){return"urlPath"in t}function dr(t,e,r){if(t>=400){let o=Ke(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}]`),T(s,!0)}let n=new TextDecoder().decode(e);try{return T(JSON.stringify(JSON.parse(n),null,2))}catch{return T(n)}}function pr(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 wt(t){let e=xe(t,""),r=Object.keys(t.environments??{}),n=[`Active: ${e||"(none)"}`,`Configured: ${r.length>0?r.join(", "):"(none)"}`];return e||n.push(`
64
+ Run: cdp env <name> --key-id=... --key-secret=... to configure.`),T(n.join(`
65
+ `))}function fr(t,e){if(!e)return T("Environment name is required.",!0);let r=Object.keys(t.environments??{});return r.length===0?T("No environments configured. Run: cdp env <name> --key-id=... --key-secret=... to configure.",!0):t.environments[e]?{cfg:{...t,env:e}}:T(`Unknown environment: "${e}". Available environments: ${r.join(", ")}`,!0)}function mr(t){return wt(t)}function gr(t,e,r,n){if(!t||!e)return T("resource and action are required",!0);let o=r.find(p=>p.name===t);if(!o)return T(`Unknown resource: ${t}. Available: ${r.map(p=>p.name).join(", ")}`,!0);let s=o.actions.find(p=>p.name===e);if(!s)return T(`Unknown action: ${e}. Available for ${t}: ${o.actions.map(p=>p.name).join(", ")}`,!0);let a=[];a.push(`${s.summary||s.name}${z(s.audience)}`),a.push(`${s.method} ${s.path}`);let i=ar(o.name,s.name),l=s.pathParams.map(p=>`${p}="..."`).join(", ");a.push("",`Usage: ${i}(${l})`);let c=n.flattenBodyParams(s.operation);if(c.length>0){a.push("","Fields:");for(let p of c){let f=p.required?" (required)":"",w=p.description?` \u2014 ${p.description}`:"";if(p.oneOf){a.push(` ${p.path}: one of:`);for(let S of p.oneOf)a.push(` ${S.title||"variant"}: { ${S.fields.map(g=>g.name).join(", ")} }`)}else a.push(` ${p.path} (${p.type})${f}${w}`)}}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 T(a.join(`
66
+ `))}function Je(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]=xt(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 xt(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 hr(t,e,r,n){if(!t||!e)return T("resource and action are required",!0);let o=r.find(c=>c.name===t);if(!o)return T(`Unknown resource: ${t}. Available: ${r.map(c=>c.name).join(", ")}`,!0);let s=o.actions.find(c=>c.name===e);if(!s)return T(`Unknown action: ${e}. Available for ${t}: ${o.actions.map(c=>c.name).join(", ")}`,!0);let a=n.flattenBodyParams(s.operation);if(a.length===0)return T("This action has no request body.");let i=Je(s,n),l=[];for(let c of a){let u=c.required?" (required)":"",d=c.description?` \u2014 ${c.description}`:"";if(c.oneOf){l.push(`${c.path}: one of:`);for(let p of c.oneOf)l.push(` ${p.title||"variant"}: { ${p.fields.map(f=>f.name).join(", ")} }`)}else l.push(`${c.path} (${c.type})${u}${d}`)}return T(`Template:
67
+ ${JSON.stringify(i,null,2)}
68
+
69
+ Fields:
70
+ ${l.join(`
71
+ `)}`)}function yo(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 yr=yo(process.env,!!process.stdout.isTTY);function bt(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="",l=!0;for(let c of a){let u=bt(c),d=bt(i),p=c.includes("\x1B]8;;");(d+u+1>s||p&&d>0&&d+u+1>s*.6)&&i.length>0&&(t.write((l?e:" ".repeat(o))+i.trimEnd()+`
72
+ `),i="",l=!1),i+=(i?" ":"")+c}i&&t.write((l?e:" ".repeat(o))+i.trimEnd()+`
73
+ `)}function wo(t,e,r){return r?`\x1B]8;;${e}\x07\x1B[4m${t}\x1B[24m\x1B]8;;\x07`:`${t} (${e})`}function Ye(t,e=yr){return t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,o)=>wo(n,o,e))}function be(t){return t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/_(.+?)_/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^#{1,6}\s+/gm,"")}function ze(t,e){let r=e??process.stdout.columns??100;return t.replace(/\r\n/g,`
74
+ `).trim().split(`
75
+ `).flatMap(n=>{n=be(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
+ `)+`
77
+ `}function wr(t){let e=B();if(t.length===0)return xo(e);if(t.length===1)return bo(e,t[0]);if(t.length===2)return vo(e,t[0],t[1]);throw new Error("usage: cdp api [group | METHOD /path | /path]")}function xo(t){for(let e of t.groups()){let r=Te(e);process.stdout.write(`${e.name.padEnd(24)} ${String(e.endpoints.length).padStart(2)} endpoints ${r}
78
+ `)}}function bo(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`);Eo(r,t)}function vo(t,e,r){let n=t.findEndpoint(e.toUpperCase(),r.startsWith("/v2")?r:"/v2"+r);if(!n)throw new Error(`no endpoint: ${e} ${r}`);vt(n,t)}function Eo(t,e){for(let r=0;r<t.length;r++){r>0&&process.stdout.write(`
79
+ `);let n=t[r];process.stdout.write(`${n.method.padEnd(5)} ${n.path.replace(/^\/v2/,"").padEnd(45)} ${n.summary}${z(n.operation?.["x-audience"]??"")}
80
+ `),So(n,e)}}function ue(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 l=`${a}${i.name.padEnd(n)}${i.type.padEnd(o)}${s>0?i.req.padEnd(s)+" ":""}`,c=Ye(be(i.desc.replace(/\n/g," ").trim()));if(r)X(process.stdout,l,c);else{let u=Math.max((process.stdout.columns||100)-l.length,20);process.stdout.write(`${l}${c.length>u?c.slice(0,u-3)+"...":c}
81
+ `)}}}function So(t,e){let r=e.flattenBodyParams(t.operation);r.length>0&&(process.stdout.write(` body:
82
+ `),ue(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=it(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
+ `),a.length>0&&process.stdout.write(` query: ${a.join(", ")}
84
+ `)}function vt(t,e){let r=process.stdout,n=t.path.replace(/^\/v2/,"");r.write(`${t.method} \u2014 ${t.summary||n}${z(t.operation?.["x-audience"]??"")}
85
+ `),t.operation.description&&r.write(`
86
+ `+ze(t.operation.description)),r.write(`
87
+ Usage:
88
+ 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=it(s.path,t.path),r.write(`
90
+ Path parameters:
91
+ `),ue(s.path,2,!0)),s.query?.length&&(r.write(`
92
+ Query parameters:
93
+ `),ue(s.query,2,!0));let a=e.flattenBodyParams(t.operation);a.length>0&&(r.write(`
94
+ Request body:
95
+ `),ue(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
+ Response 200: ${i.description}
97
+ `),i.fieldDetails.length>0&&ue(i.fieldDetails.map(u=>({name:u.name,type:u.type,req:"",desc:u.description})),2,!0));let l=new Set,c=[];for(let u of a)if(u.oneOf)for(let d of u.oneOf)l.has(d.title)||(l.add(d.title),c.push(d));if(c.length>0){process.stdout.write(`
98
+ Types:
99
+ `);for(let u=0;u<c.length;u++)u>0&&process.stdout.write(`
100
+ `),process.stdout.write(` ${c[u].title}
101
+ `),ue(c[u].fields.map(d=>({name:d.name,type:d.type,req:d.required?"required":"",desc:d.description})),4,!0)}}function Xe(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 V(t,e){let r={},n=[],o=!1,s=new Map;for(let[a,i,l]of e)s.set("--"+a,[a,l]),i&&s.set("-"+i,[a,l]);for(let a=0;a<t.length;a++){let i=t[a];if(i==="-h"||i==="--help"){o=!0;continue}let l=i.indexOf("=");if(l>0&&i.startsWith("--")){let u=s.get(i.slice(0,l));if(u){r[u[0]]=i.slice(l+1);continue}}let c=s.get(i);if(c){r[c[0]]=c[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 Et=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];function $o(t){return t.length>=2&&Et.includes(t[0].toUpperCase())&&t[1].startsWith("/")?{method:t[0],pathIdx:1}:{method:void 0,pathIdx:0}}function ko(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 Po(t){let e=t.filter(r=>!le(r)&&!Et.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 Ro(t,e){let r=t.toLowerCase();return r==="authorization"||r.includes("key")||r.includes("token")||r.includes("secret")?"***":e}async function xr(t,e){if(t.length===0){wr([]);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
+
103
+ Usage:
104
+ cdp api List all API endpoints
105
+ cdp api <group> List endpoints in a group
106
+ cdp api <path> [fields...] Make an authenticated request
107
+ cdp api <path> --help Show endpoint details
108
+
109
+ Field syntax:
110
+ key=value String body field
111
+ key:=value Raw JSON body field
112
+ key==value Query parameter
113
+ a.b.c=value Nested body field
114
+ Header:value HTTP header
115
+ @file.json Body from file
116
+ - Body from stdin
117
+
118
+ Flags:
119
+ -X, --method HTTP method (default: auto)
120
+ --jq <expr> jq filter expression
121
+ -i, --include Include response headers
122
+ -v, --verbose Show full request and response
123
+ --paginate Auto-paginate using nextPageToken
124
+ `);return}let s=B(),a=s.groups().flatMap(P=>P.endpoints),i=or(a);Po(n);let l=ko(o);if(l){let P=l.split("/").filter(Boolean),{node:A,consumed:v}=sr(i,P),_=n.find(I=>Et.includes(I.toUpperCase())),k=v.length===P.length,U=n.some(I=>I==="-X"||I==="--method"||I.startsWith("--method=")),G=n.some((I,te)=>te>0&&le(I)&&I!=="-X"&&I!=="--method"&&!I.startsWith("--method=")),ee=ir(A);if(k&&(r||A.endpoints.length===0||ee&&!U&&!G)){let I=_?A.endpoints.filter(j=>j.method===_.toUpperCase()):A.endpoints;if(I.length>0&&r)for(let j=0;j<I.length;j++)j>0&&process.stdout.write(`
125
+ `),vt(I[j],s);let te=Ge(A).filter(j=>!I.includes(j));if(te.length>0){I.length>0&&process.stderr.write(`
126
+ Sub-paths:
127
+ `);for(let j of te){let qn=j.path.replace(/^\/v2/,"");process.stderr.write(` ${j.method.padEnd(6)} ${qn}
128
+ `)}}if(I.length>0||te.length>0)return}}let c=V(t,[["method","X",!0],["jq",null,!0],["include","i",!1],["verbose","v",!1],["paginate",null,!1]]),u=c.args,d={method:c.flags.method,jq:c.flags.jq,include:!!c.flags.include,verbose:!!c.flags.verbose,paginate:!!c.flags.paginate,envFlag:e.envFlag};if(u.length===0)throw new Error("usage: cdp api <path> [fields...]");let{method:p,pathIdx:f}=$o(u);p&&(d.method=p);let w=D(),{name:S,env:g}=ie(w,d.envFlag),m=W(g,S),E=He(u.slice(f+1)),b=(d.method??"").toUpperCase()||(rr(E)?"POST":"GET"),x=ae(m,u[f]),R=E.query.toString();R&&(x+=(x.includes("?")?"&":"?")+R);let O=Ve(E),$={method:b,body:O,headers:E.headers,keyId:g.key_id,keySecret:g.key_secret,walletSecret:g.wallet_secret},C=x;do{if(d.verbose){let v=new URL(C);process.stderr.write(`> ${b} ${v.pathname}${v.search}
129
+ > Host: ${v.host}
130
+ `);for(let[_,k]of Object.entries(E.headers))process.stderr.write(`> ${_}: ${Ro(_,k)}
131
+ `);process.stderr.write(`>
132
+ `)}let P=await ce({...$,url:C});if(d.verbose&&(process.stderr.write(`< HTTP ${P.status}
133
+ `),P.headers.forEach((v,_)=>process.stderr.write(`< ${_}: ${v}
134
+ `)),process.stderr.write(`<
135
+ `)),d.include&&(process.stdout.write(`HTTP ${P.status}
136
+ `),P.headers.forEach((v,_)=>process.stdout.write(`${_}: ${v}
137
+ `)),process.stdout.write(`
138
+ `)),St(P,d.jq),!d.paginate)break;let A=Xe(C,P.body);if(!A)break;C=A}while(!0)}function St(t,e){let r=t.status>=400;if(e)try{process.stdout.write(nr(t.body,e)+`
139
+ `)}catch(n){process.stdout.write(new TextDecoder().decode(t.body)+`
140
+ `),process.stderr.write(`jq error: ${n.message}
141
+ `)}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
+ `)}catch{process.stdout.write(n+`
143
+ `)}else process.stdout.write(n+`
144
+ `)}if(r){let n=Ke(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 Uo}from"node:readline";function de(t){let e=t.groups(),r=[];for(let n of e){let o=[];for(let a of n.endpoints){let i=Io(n.name,a);i&&o.push(i)}let s=Ao(o);s.sort((a,i)=>{let l=br(a.name),c=br(i.name);if(l!==c)return l<c?-1:1;let u=vr(a.name),d=vr(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 Ao(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} ${Qe(r.method,n)}`}}return r})}function Qe(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 Io(t,e){let r=e.path.replace(`/v2/${t}`,"").replace(/^\//,""),n=r?r.split("/"):[],o=n.filter(c=>c[0]!=="{"),s=n.length>0&&n[n.length-1][0]==="{",a=st(e.path),i;n.length===0?i=Qe(e.method,!1):s&&o.length===0?i=Qe(e.method,!0):s&&o.length<=1?i=o[0]+" "+Qe(e.method,!0):i=o.join(" ");let l=e.operation?.["x-audience"]??"";return{name:i,method:e.method,path:e.path,summary:e.summary,audience:l,operation:e.operation,pathParams:a}}function br(t){let e=t.split(" ");return e.length>1?e.slice(0,-1).join(" "):""}function vr(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}}import{readFileSync as To,writeFileSync as _o,mkdirSync as Co}from"node:fs";import{join as Sr}from"node:path";var $r;$r="2.0.1";var ne=$r,kr=Lt,Oo=`${_e}/${encodeURIComponent(kr)}`,Pr="version-check.json";function Er(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 Bo(t,e){let r=Er(t),n=Er(e);return n.major!==r.major?n.major>r.major:n.minor!==r.minor?n.minor>r.minor:n.patch>r.patch}var No="https://registry.npmjs.org";function Do(t,e){let r=_e===No?"":` --registry ${_e}`;return`
145
+ Update available: ${t} \u2192 ${e}
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}
149
+
150
+ Run: cdp env <name> --key-id=... --key-secret=...`,!0)}let{name:c,env:u}=l,d=ae(W(u,c),a.urlPath),p=a.queryParams.toString();p&&(d+=(d.includes("?")?"&":"?")+p);try{let f=await ce({method:a.method,url:d,body:a.body,keyId:u.key_id,keySecret:u.key_secret,walletSecret:u.wallet_secret});return dr(f.status,f.body,f.headers)}catch(f){return T(`Request failed: ${f.message}`,!0)}}var Ho={name:"cdp",version:ne},Vo={tools:{}},$t=null;function Ir(){return $t||($t=cr(B(),de(B()))),$t}async function Go(t){let{id:e,method:r,params:n}=t;switch(r){case"initialize":ve(e,{protocolVersion:"2024-11-05",serverInfo:Ho,capabilities:Vo});break;case"notifications/initialized":break;case"tools/list":ve(e,{tools:Ir()});break;case"tools/call":{let{name:o,arguments:s}=n??{};if(!o){Ee(e,-32602,"Missing tool name");return}if(!Ir().find(i=>i.name===o)){Ee(e,-32602,`Unknown tool: ${o}`);return}try{let i=await Fo(o,s??{});ve(e,i)}catch(i){ve(e,T(`Internal error: ${i.message}`,!0))}break}case"ping":ve(e,{});break;default:e!=null&&Ee(e,-32601,`Method not found: ${r}`);break}}function _r(){let t=Uo({input:process.stdin,terminal:!1});t.on("line",e=>{if(e.trim())try{let r=JSON.parse(e);Go(r).catch(n=>{process.stderr.write(`MCP error: ${n.message}
151
+ `),r.id!=null&&Ee(r.id,-32603,n.message)})}catch{Ee(null,-32700,"Parse error")}}),t.on("close",()=>process.exit(0)),process.stderr.write(`CDP MCP server v${ne} ready
152
+ `)}import{readFileSync as us}from"node:fs";var Cr={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"}},Or={solana:{cluster:"mainnet-beta",rpc:"https://api.mainnet-beta.solana.com"},"solana-devnet":{cluster:"devnet",rpc:"https://api.devnet.solana.com"}};function Br(t,e){let r=t.toLowerCase(),n=Cr[r];if(n)return{chain:"evm",chainId:n.chainId,rpc:e||n.rpc,name:r};let o=Or[r];if(o)return{chain:"solana",cluster:o.cluster,rpc:e||o.rpc,name:r};throw new Error(`unknown network: ${t}. Supported: ${[...Object.keys(Cr),...Object.keys(Or)].join(", ")}`)}function kt(t){if(Buffer.isBuffer(t))return t.length===1&&t[0]<128?t:Buffer.concat([Nr(t.length,128),t]);let e=Buffer.concat(t.map(kt));return Buffer.concat([Nr(e.length,192),e])}function Nr(t,e){if(t<56)return Buffer.from([e+t]);let r=Q(t);return Buffer.concat([Buffer.from([e+55+r.length]),r])}function qr(t){let[e]=Lr(t,0);return e}function Lr(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,l=Dr(t.subarray(e+1,e+1+i)),c=e+1+i;return[t.subarray(c,c+l),c+l]}let n,o;if(r<=247)n=r-192,o=e+1;else{let i=r-247;n=Dr(t.subarray(e+1,e+1+i)),o=e+1+i}let s=[],a=o;for(;a<o+n;){let[i,l]=Lr(t,a);s.push(i),a=l}return[s,o+n]}function Q(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 Dr(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 Ko=1;async function M(t,e,r){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Ko++,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 jr(t,e){let r=await M(t,"eth_getTransactionCount",[e,"pending"]);return parseInt(r,16)}async function Mr(t,e){let r=await M(t,"eth_estimateGas",[e]);return BigInt(r)}async function Ur(t,e){let r=await M(t,"eth_chainId",[]),n=parseInt(r,16);if(n!==e)throw new Error(`chainId mismatch: RPC returned ${n}, expected ${e}. Wrong network?`)}async function Fr(t){let[e,r]=await Promise.all([M(t,"eth_gasPrice",[]),M(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 Jo=[0x0000000000000001n,0x0000000000008082n,0x800000000000808an,0x8000000080008000n,0x000000000000808bn,0x0000000080000001n,0x8000000080008081n,0x8000000000008009n,0x000000000000008an,0x0000000000000088n,0x0000000080008009n,0x000000008000000an,0x000000008000808bn,0x800000000000008bn,0x8000000000008089n,0x8000000000008003n,0x8000000000008002n,0x8000000000000080n,0x000000000000800an,0x800000008000000an,0x8000000080008081n,0x8000000000008080n,0x0000000080000001n,0x8000000080008008n],Yo=[[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]],$e=(1n<<64n)-1n;function Wr(t,e){return(t<<BigInt(e)|t>>BigInt(64-e))&$e}function zo(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]^Wr(r[(o+1)%5],1);for(let a=0;a<25;a+=5)t[o+a]=(t[o+a]^s)&$e}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]=Wr(t[o+s*5],Yo[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]&$e&n[o+(s+2)%5])&$e;t[0]=(t[0]^Jo[e])&$e}}function Pt(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 l=0n,c=a+i*8;for(let u=7;u>=0;u--)l=l<<8n|BigInt(o[c+u]);n[i]^=l}zo(n)}let s=Buffer.alloc(32);for(let a=0;a<4;a++){let i=n[a];for(let l=0;l<8;l++)s[a*8+l]=Number(i&0xffn),i>>=8n}return s}function Xo(t){let e=t.toLowerCase(),r=Pt(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 Hr(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===Xo(e)}var Qo=(1n<<256n)-1n;function ke(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>Qo)throw new Error(`value exceeds uint256 max: ${t}`);return e}async function Vr(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(!Hr(r))throw new Error(`invalid EIP-55 checksum: ${r}`);let i=e.value?ke(e.value):0n,l=e.nonce;if(l===void 0){if(!o)throw new Error("--from is required when --nonce is not specified (needed for nonce lookup)");l=await jr(t.rpc,o)}let{gasLimit:c,maxFeePerGas:u,maxPriorityFeePerGas:d}=e;if(!c||!u){let w=await Fr(t.rpc);u??=w.maxFeePerGas,d??=w.maxPriorityFeePerGas,c||(c=await Mr(t.rpc,{from:o,to:r,value:i>0n?"0x"+i.toString(16):void 0,data:n||void 0}),c=c*12n/10n)}d??=1000000n;let p=[Q(t.chainId),Q(l),Q(d),Q(u),Q(c),Buffer.from(r.replace(/^0x/,""),"hex"),Q(i),n?Buffer.from(n.replace(/^0x/,""),"hex"):Buffer.alloc(0),[]];return"0x02"+kt(p).toString("hex")}function Gr(t){if(!t.startsWith("0x02"))throw new Error("only EIP-1559 (type 2) transactions supported");let e=Buffer.from(t.slice(4),"hex"),r=qr(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 Zo,constants as es}from"node:crypto";var ts=`-----BEGIN PUBLIC KEY-----
153
+ MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA2Fxydgm/ryYk0IexQIuL
154
+ 9DKyiIk2WmS36AZ83a9Z0QX53qdveg08b05g1Qr+o+COoYOT/FDi8anRGAs7rIyS
155
+ uigrjHR6VrmFjnGrrTr3MINwC9cYQFHwET8YVGRq+BB3iFTB1kIb9XJ/vT2sk1xP
156
+ hJ6JihEwSl4DgbeVjqw59wYqrNg355oa8EdFqkmfGU2tpbM56F8iv1F+shwkGo3y
157
+ GhW/UOQ5OLauXvsqo8ranwsK+lqFblLEMlNtn1VSJeO2vMxryeKFrY2ob8VqGchC
158
+ ftPJiLWs2Du6juw4C1rOWwSMlXzZ6cNMHkxdTcEHMr3C2TEHgzjZY41whMwNTB8q
159
+ /pxXnIbH77caaviRs4R/POe8cSsznalXj85LULvFWOIHp0w+jEYSii9Rp9XtHWAH
160
+ nrK/O/SVDtT1ohp2F+Zg1mojTgKfLOyGdOUXTi95naDTuG770rSjHdL80tJBz1Fd
161
+ +1pzGTGXGHLZQLX5YZm5iuy2cebWfF09VjIoCIlDB2++tr4M+O0Z1X1ZE0J5Ackq
162
+ rOluAFalaKynyH3KMyRg+NuLmibu5OmcMjCLK3D4X1YLiN2OK8/bbpEL8JYroDwb
163
+ EXIUW5mGS06YxfSUsxHzL9Tj00+GMm/Gvl0+4/+Vn8IXVHjQOSPNEy3EnqCiH/OW
164
+ 8v0IMC32CeGrX7mGbU+MzlsCAwEAAQ==
165
+ -----END PUBLIC KEY-----`;function Kr(t){let e=t.startsWith("0x")?t.slice(2):t,r=/^[0-9a-fA-F]+$/.test(e);return Zo({key:ts,padding:es.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r?e:t,r?"hex":"utf8")).toString("base64")}import{createHash as ns}from"node:crypto";var At="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Rt=BigInt(At.length),rs=new Map(At.split("").map((t,e)=>[t,BigInt(e)]));function L(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*Rt+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 Z(t){let e=0n;for(let n of t)e=e*256n+BigInt(n);let r="";for(;e>0n;){let[n,o]=[e/Rt,e%Rt];r=At[Number(o)]+r,e=n}for(let n of t)if(n===0)r="1"+r;else break;return r}function N(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 pe(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 It(t){return(await M(t,"getLatestBlockhash",[{commitment:"finalized"}])).value.blockhash}async function Jr(t,e){let r=await M(t,"getBalance",[e,{commitment:"confirmed"}]);return BigInt(r.value)}async function Yr(t,e){let r=await M(t,"getMinimumBalanceForRentExemption",[e]);return BigInt(r)}async function Tt(t,e){let r=await M(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 _t=Buffer.alloc(32),Pe=L("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),Ze=L("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"),Xr=(1n<<64n)-1n;function tt(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>Xr)throw new Error(`value exceeds u64 max: ${t}`);return e}async function Qr(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?tt(e.value):0n,s=L(r);if(s.length!==32)throw new Error(`invalid Solana address: ${r} (expected 32 bytes, got ${s.length})`);let a=L(n);if(a.length!==32)throw new Error(`invalid Solana address: ${n} (expected 32 bytes, got ${a.length})`);let i;if(e.blockhash)i=L(e.blockhash);else{let S=await It(t.rpc);i=L(S)}let l=Buffer.alloc(12);l.writeUInt32LE(2,0),l.writeBigUInt64LE(o,4);let c=[s,a,_t],u=Buffer.from([1,0,1]),d=Buffer.concat([Buffer.from([2]),N(2),Buffer.from([0,1]),N(l.length),l]),p=Buffer.concat([u,N(c.length),...c,i,N(1),d]),f=Buffer.concat([Buffer.from([128]),p,N(0)]);return Buffer.concat([N(1),Buffer.alloc(64),f]).toString("base64")}function os(t,e){for(let r=255;r>=0;r--){let n=ns("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(!is(o))return{address:o,bump:r}}throw new Error("Could not find PDA")}var K=2n**255n-19n,ss=-121665n*en(121666n,K)%K;function et(t,e){return(t%e+e)%e}function Zr(t,e,r){let n=1n;for(t=et(t,r);e>0n;)e&1n&&(n=n*t%r),e>>=1n,t=t*t%r;return n}function en(t,e){return Zr(t,e-2n,e)}function is(t){let e=0n;for(let o=31;o>=0;o--)e=e<<8n|BigInt(t[o]);if(e&=(1n<<255n)-1n,e>=K)return!1;let r=et(e*e,K),n=et((r-1n)*en(et(ss*r+1n,K),K),K);return n===0n?!0:Zr(n,(K-1n)/2n,K)===1n}function zr(t,e){return os([t,Pe,e],Ze)}function as(t){if(t.length<45)throw new Error("invalid mint account data (too short)");return t[44]}async function tn(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=L(r),a=L(n),i=L(o),l=zr(s,i),c=zr(a,i),u;if(e.blockhash)u=L(e.blockhash);else{let k=await It(t.rpc);u=L(k)}let d;if(e.decimals!==void 0)d=e.decimals;else{let k=await Tt(t.rpc,o);if(!k.exists)throw new Error(`mint account not found: ${o}`);d=as(k.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>Xr)throw new Error(`value exceeds u64 max: ${p}`);process.stderr.write(`Amount: ${f} token units (decimals: ${d})
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
167
+
168
+ Usage:
169
+ cdp util <command> [flags]
170
+
171
+ Commands:
172
+ tx-encode Build an unsigned transaction (EVM or Solana)
173
+ tx-decode Decode a raw transaction hex or base64
174
+ abi-encode Encode ABI data \u2014 function calls or raw values
175
+ encrypt-key Encrypt a private key for account import
176
+
177
+ Run 'cdp util <command> -h' for command-specific help.
178
+ `,ps=`Build an unsigned transaction
179
+
180
+ Supports EVM networks (base, ethereum, arbitrum, optimism, polygon, avalanche)
181
+ and Solana networks (solana, solana-devnet). Chain is auto-detected from --network.
182
+
183
+ Usage:
184
+ cdp util tx-encode --network <name> --to <address> [flags]
185
+
186
+ Flags:
187
+ -n, --network <name> Network name (see above)
188
+ --to <address> Destination address (0x-prefixed hex or base58)
189
+ --value <amount> Value to send (wei, 0.001ether, 1gwei, 0.5sol, lamports)
190
+ --from <address> Sender address (required for nonce/gas/blockhash lookup)
191
+ -d, --data <hex> Calldata hex (EVM only)
192
+ --nonce <n> Nonce (EVM, skips RPC if provided)
193
+ --gas-limit <n> Gas limit (EVM, skips RPC if provided)
194
+ --max-fee <wei> Max fee per gas (EVM)
195
+ --max-priority-fee <wei> Max priority fee per gas (EVM)
196
+ --blockhash <hash> Recent blockhash (Solana, skips RPC if provided)
197
+ --rpc-url <url> Custom RPC URL (overrides default for network)
198
+ --token <mint_address> SPL token mint address (Solana only, builds SPL transfer)
199
+
200
+ EVM examples:
201
+ cdp util tx-encode --network base --to 0xdead --value 0.001ether --from 0x957...
202
+ cdp util tx-encode --network base --to 0xUSDC --data 0xa9059cbb... --from 0x957...
203
+ cdp util tx-encode --network base --to 0xdead --value 100 --nonce 5 --gas-limit 21000
204
+
205
+ Solana examples:
206
+ cdp util tx-encode --network solana-devnet --from <base58> --to <base58> --value 0.5sol
207
+ cdp util tx-encode --network solana-devnet --from <base58> --to <base58> --value 1000000 --token <mint>
208
+ `;function fn(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 gn(t){if(t.length===0||t[0]==="-h"||t[0]==="--help"){process.stderr.write(ds);return}let[e,...r]=t;if(e==="tx-encode")return fs(r);if(e==="tx-decode")return hs(r);if(e==="abi-encode")return gs(r);if(e==="encrypt-key"){if(r[0]==="-h"||r[0]==="--help"||r.length===0){process.stderr.write(mn),r[0]!=="-h"&&r[0]!=="--help"&&process.exit(1);return}let n=V(r,[["file","f",!0]]),o;if(n.flags.file)try{o=us(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 pn()).toString("utf-8").trim();else{process.stderr.write(mn),process.exit(1);return}if(!o)throw new Error("private key cannot be empty");process.stdout.write(Kr(o)+`
209
+ `);return}throw new Error(`unknown util command: ${e}
210
+ Run: cdp util --help`)}async function fs(t){let e=V(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(ps);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=Br(r,e.flags["rpc-url"]);if(s.chain==="solana"){if(!o)throw new Error("--from is required");let c=e.flags.token,u=e.flags.value;if(!c){let f=u?tt(u):0n;f>0n&&process.stderr.write(`Value: ${fn(f,"solana")}
211
+ `)}let d=!c&&u?tt(u):0n;if(!c&&d>0n&&s.rpc)try{let[f,w]=await Promise.all([Jr(s.rpc,o),Yr(s.rpc,0)]),S=f-d;S>0n&&S<w&&process.stderr.write(`warning: sender will have ${S} lamports remaining, below rent-exempt minimum (${w}). Account may be garbage-collected.
212
+ `)}catch{}let p;c?p=await tn(s,{from:o,to:n,value:e.flags.value,blockhash:e.flags.blockhash,mint:c}):p=await Qr(s,{from:o,to:n,value:e.flags.value,blockhash:e.flags.blockhash}),process.stdout.write(p+`
213
+ `);return}if(s.chain!=="evm")throw new Error(`unsupported chain: ${s.chain}`);let a=e.flags.value,i=a?ke(a):0n;if(i>0n&&process.stderr.write(`Value: ${fn(i,"evm")}
214
+ `),s.rpc&&(o||e.flags.nonce===void 0))try{await Ur(s.rpc,s.chainId)}catch(c){throw new Error(c.message)}let l=await Vr(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"]?ke(e.flags["max-fee"]):void 0,maxPriorityFeePerGas:e.flags["max-priority-fee"]?ke(e.flags["max-priority-fee"]):void 0});process.stdout.write(l+`
215
+ `)}var ms=`Encode ABI data \u2014 function calls or raw values
216
+
217
+ Usage:
218
+ cdp util abi-encode <signature-or-types> [args...]
219
+
220
+ Modes (auto-detected):
221
+ Function call "approve(address,uint256)" 0xSpender 1000 \u2192 selector + encoded args
222
+ Raw encoding "address,uint256" 0xSpender 1000 \u2192 encoded args only
223
+
224
+ Supported types:
225
+ address, bool, uint/uint8..uint256, int/int8..int256,
226
+ bytes1..bytes32, string, bytes
227
+
228
+ Examples:
229
+ cdp util abi-encode "approve(address,uint256)" 0xSpender 1000000
230
+ cdp util abi-encode "transfer(address,uint256)" 0xRecipient 50000000
231
+ cdp util abi-encode "balanceOf(address)" 0xAccount
232
+ cdp util abi-encode "address,uint256" 0xSpender 1000
233
+ cdp util abi-encode "uint8,bytes" 0 0xdeadbeef
234
+ `,mn=`Encrypt a private key for account import
235
+
236
+ Usage:
237
+ cdp util encrypt-key --file <path>
238
+ cdp util encrypt-key -
239
+
240
+ Options:
241
+ -f, --file <path> Path to a file containing the private key
242
+
243
+ Use - to read from stdin (e.g. piped from a secrets manager).
244
+
245
+ The file should contain a single private key \u2014 hex with or without 0x
246
+ prefix (EVM), or base58 (Solana). No JSON wrapping, no extra fields.
247
+
248
+ Encrypts with CDP's RSA public key (OAEP/SHA-256).
249
+ Output: base64 ciphertext for the encryptedPrivateKey field.
250
+
251
+ Examples:
252
+ cdp util encrypt-key --file ./exported-key.txt
253
+ vault kv get -field=key secret/wallet | cdp util encrypt-key -
254
+ `;function gs(t){if(t.length===0||t[0]==="-h"||t[0]==="--help"){process.stderr.write(ms);return}let[e,...r]=t;if(an(e)){let n=un(e,r);process.stdout.write(n+`
255
+ `)}else{let n=cn(e),o=ln(n,r);process.stdout.write(o+`
256
+ `)}}function hs(t){if(t.length===0||t[0]==="-h"||t[0]==="--help"){process.stderr.write(`Decode a raw transaction
257
+
258
+ Usage:
259
+ cdp util tx-decode <hex-or-base64>
260
+
261
+ 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)");let r;e.startsWith("0x")?r=Gr(e):r=rn(e),process.stdout.write(JSON.stringify(r,null,2)+`
263
+ `)}function hn(t){let e=D();if(t.length===0)return ys(e);if(t[0]==="clear"){let r=t[1],n;if(r&&r.includes(".")){let o=r.indexOf(".");n=Ue(e,r.slice(0,o),r.slice(o+1))}else r?n=Ue(e,r):n=Ue(e);q(e),process.stderr.write(`Cleared ${n} history ${n===1?"entry":"entries"}.
264
+ `);return}throw new Error("usage: cdp history [clear [env.action]]")}function ys(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
+ `);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 vn,writeFileSync as ws,mkdirSync as En,readdirSync as Sn,existsSync as oe,cpSync as xs,rmSync as bs}from"node:fs";import yn,{join as J,resolve as wn}from"node:path";import{fileURLToPath as vs}from"node:url";import{homedir as xn}from"node:os";import{createInterface as bn}from"node:readline";function Ot(){try{return JSON.parse(vn(he(),"utf8"))}catch{return{}}}function Ct(t){let e=se();En(e,{recursive:!0,mode:448}),ws(he(),JSON.stringify(t,null,2)+`
267
+ `,{mode:384})}function $n(){let t=yn.dirname(vs(import.meta.url));return yn.join(t,"..","skills")}function Es(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 kn(t){let e=t??$n();if(!oe(e))return[];let r=[];for(let n of Sn(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=J(e,n.name,"SKILL.md");if(!oe(o))continue;let s=vn(o,"utf8"),a=Es(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 Ss(t,e){if(!oe(t))return 0;En(e,{recursive:!0});let r=0;for(let n of Sn(t,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=J(t,n.name,"SKILL.md");if(!oe(o))continue;let s=J(e,n.name);xs(J(t,n.name),s,{recursive:!0,force:!0}),r++}return r}async function $s(){let t=process.platform==="win32"?J(process.env.USERPROFILE??xn(),".claude","skills"):J(xn(),".claude","skills");process.stderr.write(`Where should skills be installed?
268
+ `),process.stderr.write(`Tip: Not sure where your agent looks for skills? Ask your agent.
269
+
270
+ `),process.stderr.write(` 1) ${t} User \u2014 available across all projects (Recommended)
271
+ `),process.stderr.write(` 2) Other Specify a custom path
272
+
273
+ `);let e=bn({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=bn({input:process.stdin,output:process.stderr}),o=await new Promise(s=>{n.question("? Path: ",a=>{n.close(),s(a.trim())})});return o?wn(o):(process.stderr.write(`No path provided, using default.
274
+ `),t)}return wn(r)}async function ks(t){let e=Ot(),r=t||e.settings?.skillsDir,n=!1;r||(process.stdin.isTTY||(process.stderr.write(`error: no skills directory configured.
275
+ Run: cdp skills add --dir <path>
276
+ `),process.exit(1)),r=await $s(),n=!0),(!e.settings?.skillsDir||t&&e.settings.skillsDir!==r)&&(e.settings||(e.settings={}),e.settings.skillsDir=r,Ct(e));let o=$n(),s=Ss(o,r);process.stderr.write(`Installed ${s} skills to ${r}.
277
+ `),n&&process.stderr.write(`Skills will auto-update on future installs.
278
+ `)}function Ps(){let e=Ot().settings?.skillsDir,r=kn();if(r.length===0){process.stderr.write(`No bundled skills found.
279
+ `);return}let n=Math.max(...r.map(o=>o.name.length),4);process.stderr.write(`${"Name".padEnd(n+2)}${"Installed".padEnd(12)}Description
280
+ `),process.stderr.write(`${"\u2500".repeat(n+2)}${"\u2500".repeat(12)}${"\u2500".repeat(40)}
281
+ `);for(let o of r){let a=e&&oe(J(e,o.name,"SKILL.md"))?"yes":"no";process.stderr.write(`${o.name.padEnd(n+2)}${a.padEnd(12)}${o.description}
282
+ `)}process.stderr.write(`
283
+ ${r.length} skills available.`),e?process.stderr.write(` Installed to: ${e}`):process.stderr.write(" Run: cdp skills add"),process.stderr.write(`
284
+ `)}function Rs(){let t=Ot(),e=t.settings?.skillsDir;if(!e){process.stderr.write(`No skills directory configured. Nothing to remove.
285
+ `);return}if(!oe(e)){process.stderr.write(`Skills directory not found: ${e}
286
+ `),t.settings&&delete t.settings.skillsDir,Ct(t),process.stderr.write(`Cleared skillsDir from config.
287
+ `);return}let r=kn(),n=0;for(let o of r){let s=J(e,o.name);oe(s)&&(bs(s,{recursive:!0,force:!0}),n++)}t.settings&&delete t.settings.skillsDir,Ct(t),process.stderr.write(`Removed ${n} skills from ${e}.
288
+ `),process.stderr.write(`Cleared skillsDir from config.
289
+ `)}async function Pn(t){let e=t[0];if(!e||e==="-h"||e==="--help"){process.stderr.write(`Manage CDP agent skills
290
+
291
+ Usage:
292
+ cdp skills add Install/update skills to your skills directory
293
+ cdp skills add --dir <path> Install skills to a specific directory
294
+ cdp skills list List available skills from this package
295
+ cdp skills remove Remove installed skills and clear config
296
+
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 ks(r);break;case"list":Ps();break;case"remove":Rs();break;default:process.stderr.write(`error: unknown skills subcommand: ${e}
298
+ Run: cdp skills --help
299
+ `),process.exit(1)}}import{writeFileSync as Is,readFileSync as Ts,unlinkSync as _s,mkdtempSync as Cs}from"node:fs";import{tmpdir as Os}from"node:os";import{join as An}from"node:path";import{execSync as Bs,execFileSync as Ns}from"node:child_process";import{createInterface as As}from"node:readline/promises";async function Rn(t,e){if(!e&&!process.stdin.isTTY)throw new Error("interactive prompts require a TTY");let r=As({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 rt=null;function Ae(){if(rt)return rt;try{return rt=de(B()),rt}catch{return[]}}async function In(t,e,r,n,o=[]){let s=Ae().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((Tn(e,a)??"{}")+`
300
+ `);return}let l=[],c=[];for(let f of r)l.length<e.pathParams.length&&!le(f)?l.push(f):c.push(f);if(l.length<e.pathParams.length)throw new Error(`missing required argument(s): ${e.pathParams.slice(l.length).join(", ")}`);let u=c.filter(f=>!le(f));if(u.length>0){let f=e.pathParams.map(w=>`<${w}>`).join(", ");throw new Error(`unexpected positional argument(s): ${u.join(", ")}
301
+ This action takes ${e.pathParams.length} positional arg(s): ${f||"(none)"}`)}let d=[...l,...c],p="";for(let f=0;f<e.pathParams.length;f++){let w=l[f].includes("=")?l[f].split("=")[0]:l[f];if(o.includes(w)){let S=s.actions.find(g=>g.name.endsWith(` ${w}`));if(S){let g=S.pathParams.map(m=>` <${m}>`).join("");p=`Did you mean: cdp ${t} ${S.name}${g}`;break}}}if(p&&c.length>0&&!i)throw new Error(`unexpected argument(s): ${c.join(" ")}
302
+ ${p}`);try{return await Ds(s,e,t,d,c,i,a,n)}catch(f){throw new Error(p?`${f.message}
303
+ ${p}`:f.message)}}async function Ds(t,e,r,n,o,s,a,i){let l=e.path.replace(/^\/v2/,"");for(let x=0;x<e.pathParams.length;x++){let R=n[x];if(!R||R.trim()==="")throw new Error(`missing required argument: <${e.pathParams[x]}>`);l=l.replace(`{${e.pathParams[x]}}`,R)}let c=js(o,a,e.operation),u=He(c),d=D(),p=xe(d,i.envFlag),f=`${t.name}.${e.name.replace(/ /g,"_")}`;if(s&&c.length>0){let x={};if(p){let R=pt(d,p,f);if(R)for(let[O,$]of Object.entries(R.values))x[O]=ft($)}u.body=Ws(c,x)}else if(s&&o.length===0&&p){let x=pt(d,p,f);if(x&&Object.keys(x.values).length>0){for(let[R,O]of Object.entries(x.values))H(u.body,R,ft(O));process.stderr.write(`reusing saved values for ${p}:${f}
304
+ `)}}let w=Ve(u);if(i.edit&&s?w=_n(w,e,a):s&&(!w||w.length===0)&&(w=await Us(w,e,a,r)),i.dryRun){process.stderr.write(`would ${e.method} ${l}
305
+ `);let x=u.query.toString();if(x&&process.stderr.write(`query: ${x}
306
+ `),w)try{process.stdout.write(JSON.stringify(JSON.parse(new TextDecoder().decode(w)),null,2)+`
307
+ `)}catch{process.stdout.write(new TextDecoder().decode(w)+`
308
+ `)}return}let{name:S,env:g}=ie(d,i.envFlag);if(a.requiresWalletAuth(e.operation)&&!g.wallet_secret)throw new Error(`This operation requires a wallet secret.
309
+ Configure: cdp env ${S} --wallet-secret <secret>
310
+ Generate one at: https://portal.cdp.coinbase.com/products/server-wallet/accounts`);let m=ae(W(g,S),l),E=u.query.toString();E&&(m+=(m.includes("?")?"&":"?")+E);let b=m;do{let x=await ce({method:e.method,url:b,body:w,headers:u.headers,keyId:g.key_id,keySecret:g.key_secret,walletSecret:g.wallet_secret});if(b===m&&x.status<400&&s&&w&&p&&Gt(d))try{let O={};(function $(C,P){for(let[A,v]of Object.entries(P)){let _=C?`${C}.${A}`:A;typeof v=="object"&&v&&!Array.isArray(v)?$(_,v):O[_]=JSON.stringify(v)}})("",JSON.parse(new TextDecoder().decode(w))),Kt(d,p,f,O),q(d)}catch{}if(St(x,i.jq),!i.paginate)break;let R=Xe(b,x.body);if(!R)break;b=R}while(!0)}function qs(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 Tn(t,e){let r=Je(t,e);if(Object.keys(r).length===0)return null;let n=JSON.stringify(r,null,2),o=qs(t,e);if(o.size===0)return n;let s=n.split(`
311
+ `),a=[];for(let i=0;i<s.length;i++){a.push(s[i]);for(let[l,c]of o){let u=l.split(".").pop();if(Ls(s,i,u)){let p=(s[i].match(/^(\s*)/)?.[1]??"")+" ";for(let f of c)for(let w of f.fields)a.splice(a.length-1,0,`${p}// ${JSON.stringify(w.name)}: ${JSON.stringify(xt(w))}`);o.delete(l);break}}}return a.join(`
312
+ `)}function Ls(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 js(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 Ms(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 Us(t,e,r,n){let o=Ms(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(l=>{let u=r.resolve(a[l])?.type;return u==="array"||u==="object"});if(!process.stdin.isTTY){let l=s.map(c=>{let u=r.resolve(a[c]);return` ${c} ${u?.type||"string"} required`}).join(`
313
+ `);throw new Error(`this action requires a request body
314
+
315
+ Required fields:
316
+ ${l}
317
+
318
+ Provide fields inline:
319
+ cdp ${n} ${e.name} ${s.map(c=>`${c}=<value>`).join(" ")}
320
+
321
+ Or use --template to see the full body shape:
322
+ cdp ${n} ${e.name} --template
323
+ `)}if(s.length<=3&&!i){let l=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}}),c=await Rn(l);return new TextEncoder().encode(JSON.stringify(c))}return process.stderr.write(`This action requires structured input. Opening editor with template.
324
+ `),_n(t,e,r)}function Fs(){if(process.platform!=="win32")return"vi";try{return Bs("where code",{stdio:"pipe"}),"code --wait"}catch{}return"notepad"}function _n(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??Fs();(n.trim()==="code"||n.trim().endsWith("/code"))&&(n+=" --wait");let o=!t||t.length===0?Tn(e,r)??"{}":(()=>{try{return JSON.stringify(JSON.parse(new TextDecoder().decode(t)),null,2)}catch{return new TextDecoder().decode(t)}})(),s=An(Cs(An(Os(),"cdp-")),"request.json");Is(s,o);try{let[a,...i]=n.split(/\s+/);Ns(a,[...i,s],{stdio:"inherit",env:Me()});let l=Hs(Ts(s,"utf8"));return JSON.parse(l),new TextEncoder().encode(l)}catch(a){throw new Error(a.message?.includes("Unexpected")?`edited file is not valid JSON: ${a.message}`:`editor: ${a.message}`)}finally{try{_s(s)}catch{}}}function Ws(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 Hs(t){let e=t.split(`
325
+ `),r=[];for(let n of e)n.trimStart().startsWith("//")||r.push(n);return r.join(`
326
+ `).replace(/,(\s*[}\]])/g,"$1")}function Cn(t,e){let r=B(),n=process.stderr;n.write(`${e.summary||e.name}${z(e.audience)}
327
+ `);let o=e.operation?.description;o&&n.write(`
328
+ `+ze(o));let s=`cdp ${t} ${e.name}`;for(let g of e.pathParams)s+=` <${g}>`;n.write(`
329
+ Usage:
330
+ ${s} [fields...]
331
+ `);let a=r.getParameters(e.operation),i=a.filter(g=>g.in==="path");if(i.length>0){n.write(`
332
+ Arguments:
333
+ `);let g=Math.max(...i.map(m=>m.name.length));for(let m of i){let E=m.schema?.type||"string",b=m.required?" required":"",x=(m.description||m.schema?.description||"").replace(/\n/g," "),R=` <${m.name}>${" ".repeat(Math.max(1,g-m.name.length+2))}${E}${b} `;X(n,R,x)}}let l=r.flattenBodyParams(e.operation);if(l.length>0){n.write(`
334
+ Fields:
335
+ `);let g=Math.max(...l.map(m=>m.path.length));for(let m of l){let E=m.required?"required":"",b=" ".repeat(Math.max(1,g-m.path.length+2)),x=" ".repeat(Math.max(1,8-m.type.length)),R=E?" ":" ",O=m.type==="array"||m.type==="object"?" (use :=json)":"",$=Ye(be((m.description||"").replace(/\n/g," "))),C=$.match(/^(.*?)(\[[-a-z0-9]+(?:,\s*[-a-z0-9]+)+\])(.*)$/i),P,A=null;C?(P=C[1].trim(),A=C[2]):P=$;let v=` ${m.path}${b}${m.type}${x}${E}${R}`;X(n,v,P+O),A&&X(n," ".repeat(v.length),A)}}let c=a.filter(g=>g.in==="query");if(c.length>0){n.write(`
336
+ Query params (use == syntax):
337
+ `);let g=Math.max(...c.map(m=>m.name.length));for(let m of c){let E=m.schema?.type||"string",b=(m.description||m.schema?.description||"").replace(/\n/g," ");m.schema?.enum?.length&&(b+=(b?" ":"")+`[${m.schema.enum.join(", ")}]`);let x=` ${m.name}${" ".repeat(Math.max(1,g-m.name.length+2))}${E} `;X(n,x,b)}}let u=l.length>0,d=r.getResponseInfo(e.operation),p=d&&d.fields.includes("nextPageToken");if(n.write(`
338
+ Flags:
339
+ `),u&&n.write(` --template Show request body template from spec
340
+ `),n.write(` --dry-run Preview request without sending
341
+ `),u&&n.write(` --edit Open body in $EDITOR
342
+ `),n.write(` --jq <expr> Filter response with jq
343
+ `),p&&n.write(` --paginate Auto-paginate using nextPageToken
344
+ `),d&&d.fieldDetails.length>0){n.write(`
345
+ Response:
346
+ `);let g=Math.max(...d.fieldDetails.map(m=>m.name.length));for(let m of d.fieldDetails){let E=` ${m.name.padEnd(g+2)}${m.type.padEnd(8)}`;X(n,E,m.description)}}let f=Je(e,r),w=f&&Object.keys(f).length>0,S=c.length>0;if(w||S){if(n.write(`
347
+ Example:
348
+ `+s),w)for(let[g,m]of Object.entries(f))typeof m=="string"&&!m.startsWith("<")?n.write(` ${g}=${m}`):typeof m=="object"&&n.write(` '${g}:=${JSON.stringify(m)}'`);if(S)for(let g of c){let m=g.schema?.example||g.schema?.default||`<${g.name}>`;n.write(` ${g.name}==${m}`)}n.write(`
349
+ `)}}function On(t){let e=Ae().find(r=>r.name===t);e||(process.stderr.write(`error: unknown resource: ${t}
350
+ Run: cdp api
351
+ `),process.exit(1)),process.stderr.write(`Manage ${e.name}
352
+
353
+ 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}${z(r.audience)}
355
+ `)}process.stderr.write(`
356
+ Flags:
357
+ --template Show request body template from spec
358
+ --dry-run Show assembled request without sending
359
+ --edit Open request body in $EDITOR
360
+ --jq <expr> jq filter expression for response
361
+ --paginate Auto-paginate using nextPageToken
362
+ `)}var Ie=class extends Error{constructor(e){super(e),this.name="HelpExit"}};function Bn(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 Nn(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 w=p.split("=")[0],S=n.children.get(w);if(S?.action){let g=S.action.pathParams.map(E=>` <${E}>`).join(""),m=i.length>0?`cdp ${r} ${i.join(" ")}`:`cdp ${r}`;throw new Error(`Did you mean: ${m} ${S.action.name.split(" ").pop()}${g}`)}}break}if(o)return{action:o,remaining:e.slice(s),siblingNames:a};let l=e[i.length],c=i.length>0?`cdp ${r} ${i.join(" ")}`:`cdp ${r}`,u=Vs(n,r);throw l&&l!=="--help"&&l!=="-h"?new Error(`unknown subcommand "${l}" for ${c}
363
+
364
+ Available actions:
365
+ ${u}`):new Ie(`${c}
366
+
367
+ Available actions:
368
+ ${u}`)}function Vs(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(`
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[zs]=process.versions.node.split(".").map(Number);zs<22&&(process.stderr.write(`cdp requires Node.js ${22}+. You have: ${process.versions.node}
370
+ `),process.exit(1));try{let t=Js(Ks(Ys(import.meta.url)),Ut);qt(JSON.parse(Gs(t,"utf8")))}catch{}function Xs(){let t=Ae(),r=B().groups();return`CLI for the Coinbase Developer Platform API
371
+
372
+ Usage:
373
+ cdp <resource> [action] [fields...]
374
+ cdp <command> [args...]
375
+
376
+ Resources:
377
+ ${t.map(o=>{let s=r.find(i=>i.name===o.name),a=s&&Te(s)||o.name;return` ${o.name.padEnd(30)}${a} (${o.actions.length} actions)`}).join(`
378
+ `)}
379
+
380
+ Commands:
381
+ env [name] Manage environments and API keys
382
+ api [path] [fields...] Raw API access / browse endpoints
383
+ util <command> Client-side utilities (tx-encode, tx-decode, abi-encode, encrypt-key)
384
+ skills <command> Manage agent skills (add, list, remove)
385
+ history [clear] View or clear saved request history
386
+ mcp MCP server (invoked by AI agents)
387
+
388
+ Global Flags:
389
+ -e, --env <name> Environment to use (overrides default)
390
+ -V, --version Show version
391
+ -h, --help Show help
392
+ `}async function Qs(){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 ${ne}
393
+ `);return}if(Bt=Ar(),r.length===0||r[0]==="-h"||r[0]==="--help"||r[0]==="help"){process.stderr.write(Xs());return}let[n,...o]=r;if(n==="env"){let s=V(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
+
395
+ Usage:
396
+ cdp env List all environments
397
+ cdp env <name> Switch to or set up an environment
398
+ cdp env <name> --key-file key.json Import from CDP key file
399
+ cdp env <name> --key-id=... --key-secret=... Configure inline
400
+ cdp env <name> --wallet-secret-file secret.txt Add wallet secret
401
+ cdp env <name> --remove Remove an environment
402
+
403
+ Flags:
404
+ -k, --key-file <f> Import from CDP API key JSON file
405
+ --key-id <id> API key ID
406
+ --key-secret <sec> API key secret
407
+ --url <url> Custom base URL
408
+ --remove Remove an environment
409
+ --wallet-secret <sec> Wallet secret (inline)
410
+ -w, --wallet-secret-file <f> Import wallet secret from file
411
+ --remove-wallet-secret Remove wallet secret only
412
+ --plaintext Store secrets in config file instead of OS keyring
413
+ `);return}await tr(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 xr(o,{envFlag:e});else if(n==="history"){let s=V(o,[]);if(s.help){process.stderr.write(`View or clear saved request history
414
+
415
+ Usage:
416
+ cdp history Show all saved history
417
+ cdp history clear Clear all history
418
+ cdp history clear <env> Clear history for an environment
419
+ cdp history clear <env>.<action> Clear a specific entry
420
+ `);return}hn(s.args)}else if(n==="util")await gn(o);else if(n==="skills"){await Pn(o);return}else if(n==="mcp"){if(V(o,[]).help){process.stderr.write(`MCP server for AI agent integration
421
+
422
+ Usage:
423
+ cdp mcp Start MCP server over stdio
424
+
425
+ The MCP server implements the Model Context Protocol (JSON-RPC over
426
+ stdin/stdout) and exposes all CDP API resources as tools. It is
427
+ typically invoked automatically by AI agents, not run directly.
428
+ `);return}_r();return}else{let s=Ae().find(c=>c.name===n);if(s||(process.stderr.write(`error: unknown command "${n}"
429
+ Run: cdp --help
430
+ `),process.exit(1)),o.length===0||o[0]==="-h"||o[0]==="--help"){On(n);return}let a=Bn(s.actions),i=Nn(a,o,n),l=V(i.remaining,[["template",null,!1],["dry-run",null,!1],["edit",null,!1],["jq",null,!0],["paginate",null,!1]]);if(l.help){Cn(n,i.action);return}await In(n,i.action,l.args,{template:!!l.flags.template,dryRun:!!l.flags["dry-run"],edit:!!l.flags.edit,paginate:!!l.flags.paginate,jq:l.flags.jq,envFlag:e},i.siblingNames)}}var Bt;Qs().catch(t=>{t instanceof Ie&&(process.stderr.write(t.message+`
431
+ `),process.exit(0)),process.stderr.write(`error: ${t.message}
432
+ `),process.exit(1)}).finally(async()=>{if(!Bt||!process.stderr.isTTY)return;let t=await Bt.catch(()=>"");t&&process.stderr.write(t)});