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