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