@coinbase/cdp-cli 2.0.62 → 2.0.64

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