@truebit/cli 1.120.0-beta.208 → 1.120.0-beta.209

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.
Files changed (2) hide show
  1. package/build/index.mjs +1 -1
  2. package/package.json +2 -2
package/build/index.mjs CHANGED
@@ -224,7 +224,7 @@ API Task response`)}
224
224
  `,r+=Ii.green(JSON.stringify(x,null,2)),console.log(`API Task executed with status - ${Ii.green("OK")} `),console.log(r)}else throw console.info(`Axios call - ${Ii.red("ERROR")} `),console.log(r),new Error(`Invalid message input ${w}`)};import{Wallet as Pke}from"ethers";function jK(e){return/^[a-f0-9]{64}$/gi.test(e)}function HK(e){try{new Pke(e)}catch{return!1}return!0}var vc=e=>{let t=e.split("_");return!!jK(t[t.length-1])};function Lp(e){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e))throw new Error("Invalid API key format")}import{ethers as kke}from"ethers";import gw from"axios";async function zK(e,t,n,a,r,i){let s={user:e,namespace:t,nonce:BigInt(n),deadline:a,signatureMeta:r};try{let f=await po(),l={...s};return l.nonce=String(s.nonce),await f.post("user/relayer/namespace",l,{params:{fromSetup:i}})}catch(f){throw gw.isAxiosError(f)?f.response?new Error(`The server responding with an error - ${f.response.status+" - "+f.response.statusText+" - "+f.response.data.message}.`):f.request?new Error(`The server is not responding - ${f.message}.`):new Error(`There was an error in the communication with the server - ${f.message}.`):typeof f=="string"?new Error(`There was an error in the communication with the server -> ${f}`):new Error("There was an error in the communication with the server.")}}async function VK(e,t,n,a,r){let i={user:e,apiKeyHash:t,deadline:n,signatureMeta:a};try{return await(await po()).post("user/relayer/auth",i,{params:{fromSetup:r}})}catch(s){throw gw.isAxiosError(s)?s.response?new Error(`The server responding with an error - ${s.response.status+" - "+s.response.statusText+" - "+s.response.data.message}.`):s.request?new Error(`The server is not responding - ${s.message}.`):new Error(`There was an error in the communication with the server - ${s.message}.`):typeof s=="string"?new Error(`There was an error in the communication with the server -> ${s}`):new Error("There was an error in the communication with the server.")}}async function WK(e,t,n,a,r,i,s){let f={user:e,namespace:t,taskName:n,task:a,nonce:BigInt(r),deadline:i,signatureMeta:s};try{let l=await po(),d={...f};return d.nonce=String(f.nonce),await l.post("user/relayer/task",d)}catch(l){throw gw.isAxiosError(l)?l.response?new Error(`The server responding with an error - ${l.response.status+" - "+l.response.statusText+" - "+l.response.data.message}.`):l.request?new Error(`The server is not responding - ${l.message}.`):new Error(`There was an error in the communication with the server - ${l.message}.`):typeof l=="string"?new Error(`There was an error in the communication with the server -> ${l}`):new Error("There was an error in the communication with the server.")}}async function kb(e,t,n=null,a=Tt("blockchainEnv")){Sa(e,"Namespace");let r,i=dn(a),s=Tt("address");if(!s)throw`Please provide an address property in '${cs()}/.truebit/secret.json'`;return n?r=await i.taskRegistry.registerTaskNamespace(e):r=await Rke(s,e,i,t),r}async function Rke(e,t,n,a){let r=await n.taskRegistry.getEIP712Domain(),i={RegisterTaskNamespaceMeta:[{name:"user",type:"address"},{name:"namespace",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},s=BigInt(await n.taskRegistry.nonces(e)),f={user:kke.getAddress(e),namespace:t,nonce:s,deadline:Math.floor(Date.now()/1e3)+3600},l=await n.utils.signMeta(r,i,f);return Date.now()/1e3>=f.deadline&&(f.deadline=Math.floor(Date.now()/1e3)+7200,l=await n.utils.signMeta(r,i,f)),(await zK(e,t,f.nonce,f.deadline,l,a)).status==201}async function GK(e,t,n,a,r){let i=await r.taskRegistry.getEIP712Domain(),s={Task:[{name:"taskId",type:"string"},{name:"meta",type:"string"},{name:"active",type:"bool"}],RegisterTaskMeta:[{name:"user",type:"address"},{name:"namespace",type:"string"},{name:"taskName",type:"string"},{name:"task",type:"Task"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},f={user:e,namespace:t,taskName:n,task:{taskId:a.taskId,meta:a.meta,active:a.active},nonce:BigInt(await r.taskRegistry.nonces(e)),deadline:Math.floor(Date.now()/1e3)+3600},l=await r.utils.signMeta(i,s,f);return Date.now()/1e3>=f.deadline&&(f.deadline=Math.floor(Date.now()/1e3)+7200,l=await r.utils.signMeta(i,s,f)),(await WK(e,t,n,a,f.nonce,f.deadline,l)).status==201}async function KK(e){return await(await $0()).post("api/filesystem/push",us({taskId:e})).catch(N0)}async function YK(e,t){let n=Tt("blockchainEnv");return await dn(n).taskRegistry.getLatestVersion(e,t)}async function ZK(e,t,n,a=null){let r=Tt("blockchainEnv"),i=dn(r),s=!1;try{if(a)s=await i.taskRegistry.registerTask(t,n,e);else{let f=Tt("address");if(!f)throw Error(`Please provide an address property in '${cs()}/.truebit/secret.json'`);s=await GK(f,t,n,e,i)}}catch(f){let l=f.message,d=l.match(/execution reverted: "(.*?)" /)?.[1];throw d?new Error(`Trying to register a task -> ${d}`):new Error(`Trying to register a task -> ${l}`)}return s}async function XK(e,t,n,a,r){if(!vc(n))throw new Error("Invalid taskId");if(a)try{a=JSON.stringify(a)}catch{throw new Error("Meta information cannot be serialized as JSON")}let i=null;try{await KK(n),await ZK({taskId:n,meta:a||"",active:!0},e,t,r),i=await YK(e,t)}catch(s){if(s instanceof Error)throw s;if(typeof s=="string")throw new Error(s)}return i}async function JK(e,t,n){let a=Tt("blockchainEnv"),r=dn(a),i=await r.taskRegistry.getLatestVersion(e,t);return await r.taskRegistry.setTaskLabel(e,t,i,n)}import*as Rb from"fs";import*as eY from"path";var tY=async(e,t,n)=>{if(console.log("Executing the function Task"),!vc(t))throw"Invalid task id";let a={status:"",result:""},r=await $0(),i=await r.post("api/execution/",us({taskId:t,input:n})).catch(N0),s=i.data.executionId;return console.log(`Execution Id: ${s}`),i.data.payload?(QK(e,i.data.payload),a.status=i.data.payload.status,a.result=i.data.payload.output?.result?i.data.payload.output?.result:""):await new Promise(f=>{let l=setInterval(async()=>{try{let d=await r.get(`api/execution/${s}`);d.data&&d.data.status!="running"&&(QK(e,d.data),clearInterval(l),a.status=d.data.status,a.result=d.data.output?.result?d.data.output?.result:"",f())}catch(d){console.error(`Error polling execution status: ${d}`),clearInterval(l),a.status="failed",a.result=`Polling error: ${d}`,f()}},1e3);setTimeout(()=>{clearInterval(l),a.status="timeout",a.result="Task execution timed out after 30 seconds",console.error("Task execution timed out after 30 seconds"),f()},3e4)}),a};function QK(e,t){if(console.log(`Task executed with status: ${t.status}`),t.output)if(console.log(`Task executed with result: ${t.output.result}`),t.output.metering){console.log("Task resource usage:");let n=t.output.metering,a=(i,s)=>{if(s==0)return"N/A";let f=i/s;return f<1?"Short":Number(f.toFixed(0))},r={Gas:{Unit:"Steps",Limits:n.limits.gas,Peak:"N/A","Last status":n.last.steps,Capacity:a(n.limits.gas,n.last.steps)},"Nested calls":{Unit:"Calls",Limits:n.limits.call,Peak:n.peak.call,"Last status":n.last.call,Capacity:a(n.limits.call,n.peak.call)},"Frame memory":{Unit:"Bytes",Limits:n.limits.frame,Peak:n.peak.frame,"Last status":n.last.frame,Capacity:a(n.limits.frame,n.peak.frame)},"System memory":{Unit:"64 Kb pages",Limits:n.limits.memory,Peak:n.peak.memory,"Last status":"\u{1D6AB} "+n.last.memoryGrowDelta,Capacity:a(n.limits.memory,n.peak.memory)}};if(console.table(r),e.updateConfig){let i=eY.join(process.cwd(),"config.json");try{let s=Rb.readFileSync(i),f=JSON.parse(s.toString());f.run.limits.gas=String(n.last.steps),f.run.limits.call=String(n.peak.call),f.run.limits.frame=String(n.peak.frame),f.run.limits.memory=String(n.limits.memory),Rb.writeFileSync(i,JSON.stringify(f)),console.log("Task limits updated with last/peak values (--update-config)")}catch(s){console.log(`Error updating config file at '${i}': '${s}', (--update-config)`)}}}else console.log("No task resource usage reported.")}async function nY(e){try{let n=await(await $0()).post("api/instrumentation",us({taskId:`${e}`})).catch(N0);if(n.data.error?.status===!0)if(n.data.error.message)console.log(`Instrumentation failed: ${n.data.error?.message}`);else throw"Malformed instrumentation service error message";else if(n.data.payload&&n.data.payload.instrumentedTaskId)console.log("Your function task is ready."),console.log(`Use the following TaskId for execution or deployment:
225
225
  ${n.data.payload.instrumentedTaskId}`);else throw"Malformed instrumentation service success message";return n.data.payload.instrumentedTaskId}catch(t){throw console.error(t),t}}import*as aY from"readline";import{ethers as Oke}from"ethers";async function rY(){let e=Wa(),t=e!==null,n=aY.createInterface({input:process.stdin,output:process.stdout}),a=i=>new Promise(s=>n.question(i,s)),r=0;if(t&&e.privateKey&&e.address)r=1;else if(t)switch(console.log(Jt.SETUP_STEP1),(await a("Press [Y] to proceed or [N] to skip: ")).trim().toUpperCase()){case"Y":r=2;break;case"N":r=3;break;default:console.log("Invalid input. Please enter Y or N."),n.close();return}switch(r){case 1:ub(),console.log(Jt.SETUP_STEP1_SCENARIO1_P1);break;case 2:{ub();let i=Oke.Wallet.createRandom(),s=i.privateKey,f=i.address;_p({privateKey:s,address:f}),console.log(`
226
226
  Setting up your new wallet...`),console.log(Jt.SETUP_STEP1_SCENARIO2(f));break}case 3:ub(),console.log(Jt.SETUP_STEP1_SCENARIO3),process.exit(1);break;default:console.log("An unexpected error occurred.");break}n.close()}async function iY(e){try{console.log("Fetching execution status...");let n=await(await $0()).get(`api/execution/${e}`).catch(N0);if(n.data.message)throw n.data.message;console.log("Task execution status: ",n.data.status),n.data.output&&console.log("Task execution output: ",n.data.output)}catch(t){console.error(`Couldn't fetch execution status for executionId ${e}: ${t}`)}}var sY=pt(nw(),1),Bp=class{tokens=[];authInputs;parse(t,n){let a=this.parseKeyValuePairs(n);if(t.length==0){this.authInputs=a;return}let r=Object.keys(a);if(t.every(i=>r.includes(i))){let i={};for(let s of t)i[s]=a[s];this.authInputs=i}else throw new Error(`Invalid authString: ${t} are required`)}parseKeyValuePairs(t){try{let n=t.split(","),a={};for(let r of n){let[i,s]=r.split(":");a[i.trim()]=s.trim()}return a}catch{throw new Error("Invalid auth string")}}},Ob=class extends Bp{tokens=["accessKey","secretKey"];constructor(t){super(),this.parse(this.tokens,t)}authHeaders(t){return sY.default.sign(t,{accessKeyId:this.authInputs.accessKey,secretAccessKey:this.authInputs.secretKey}).headers||{}}},$b=class extends Bp{tokens=["username","password"];constructor(t){super(),this.parse(this.tokens,t)}authHeaders(t){return{Authorization:`Basic ${btoa(`${this.authInputs.username}:${this.authInputs.password}`)}`}}},Nb=class extends Bp{tokens=[];constructor(t){super(),this.parse([],t)}authHeaders(t){return{...this.authInputs}}};var Ei;(function(e){e.AWS_SIGNATURE="aws-signature",e.BASIC_AUTH="basic-auth",e.CUSTOM_HEADER="custom-header"})(Ei||(Ei={}));var vw=(e,t)=>{switch(e){case Ei.AWS_SIGNATURE:return new Ob(t);case Ei.BASIC_AUTH:return new $b(t);case Ei.CUSTOM_HEADER:return new Nb(t);default:throw new Error(`Invalid authentication method specified. Should be one of <${Object.values(Ei)}>`)}};import Nke from"chalk";import{ethers as Dke}from"ethers";async function fY(e,t,n,a,r,i,s){console.log("Deploying the API Authentication Credentials");try{if(!HK(i))throw"Invalid private key provided";if(!Dke.isAddress(s))throw"Invalid address provided";if(vw(a,r),!vc(e))throw"Invalid taskId";await(await $0()).post("api/api-credentials",us({taskId:e,namespace:t,taskName:n,authString:r,method:a})).catch(N0),console.log("The credentials were deployed "+Nke.green("Successfully"))}catch(f){throw`There was an Error deploying credentials:
227
- Couldn't push api credentials to remote server: ${f}`}}import{inspect as eOe}from"util";import ua from"ora";import{v4 as tOe}from"uuid";import{ethers as Yb}from"ethers";var oY={name:"@truebit/cli",version:"1.120.0-beta.208",private:!1,description:"truebit-cli is a basic command line that allows interaction between users and truebit nextgen node.",author:{name:"Truebit Co.",url:"https://truebit.io/"},license:"https://truebit.io/terms/",repository:{type:"git",url:"https://github.com/TruebitProtocol"},homepage:"https://truebit.io/",main:"build/index.mjs",module:"build/index.mjs",types:"build/types/index.d.ts",type:"module",scripts:{prebuild:"rimraf build logs","prebuild:dev":"rimraf build logs","build:dev":"tsc && chmod +x build/index.mjs",build:"NODE_ENV=production node esbuild.config.mjs && chmod +x build/index.mjs",dev:"export NODE_ENV=development && npx nodemon",test:"vitest run --passWithNoTests tests/"},dependencies:{axios:"1.12.1",chalk:"5.6.2",colors:"1.4.0",commander:"14.0.1",ethers:"6.15.0",figlet:"1.9.1","openapi-enforcer":"1.23.0",ora:"8.2.0","public-ip":"7.0.1","ts-retry":"6.0.0",uuid:"13.0.0"},bin:{truebit:"build/index.mjs"},files:["build"],devDependencies:{"@types/figlet":"1.7.0","@vitest/coverage-v8":"3.2.4",esbuild:"^0.25.9",typescript:"5.9.2",vitest:"3.2.4"},engines:{node:">=22.13.0"}};import{createInterface as Hke}from"node:readline/promises";import kf from"chalk";import qp from"axios";import{ethers as xw}from"ethers";import{randomBytes as Bke}from"crypto";import{v4 as qke}from"uuid";import{ethers as Db}from"ethers";async function dY(e,t=Tt("blockchainEnv")){Lp(e);let n=dn(t),a=Db.keccak256(Db.toUtf8Bytes(e));return await n.authorization.registerAuthorization(a),a}async function Lb(e,t,n=Tt("blockchainEnv"),a=Tt("address")){Lp(e);let r=dn(n),i=await r.authorization.getEIP712Domain(),s=await r.authorization.nonces(a),f=Math.floor(Date.now()/1e3)+3600,l={RegisterMeta:[{name:"user",type:"address"},{name:"apiKeyHash",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},d=Db.keccak256(Db.toUtf8Bytes(e)),p={user:a,apiKeyHash:d,nonce:Number(s),deadline:f},b=await r.utils.signMeta(i,l,p);return(await VK(a,d,f,b,t)).status==201?d:null}import{isTooManyTries as lY,retryAsync as cY}from"ts-retry";var uY="0x0000000000000000000000000000000000000000";async function pY(e){let t=!0;return e===""?(t=!1,console.log("An email address is required. Please provide your email address to proceed.")):new RegExp(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(e)?await Uke(e)&&(t=!1,console.log("The provided email address is already in use. Please enter a different email address.")):(t=!1,console.log("The email address provided is not valid. Please try again.")),t}function gd(e){return e==="Y"||e==="N"}function mY(e){return!xw.isAddress(e)||e.length!==42||!e.startsWith("0x")}async function hY(){let e=await Fke();try{if(!await Lb(e,!0))throw Error("The API key could not been registered.")}catch(t){let n=t.message;if(n)throw Error(`There was an error registering the API key -> ${n}`)}return e}async function bY(){let e=await jke();try{if(!await kb(e,!0))throw Error("The namespace could not been registered.")}catch(t){let n=t.message,a=n?n.match(/execution reverted: "(.*?)" /)?.[1]:null;if(a)throw Error(`There was an error registering the namespace -> ${a}`);if(n)throw Error(`There was an error registering the namespace -> ${n}`)}return e}async function Uke(e){let t=await po();try{return(await t.get(`userexistence/${e}`)).data===!0}catch(n){if(qp.isAxiosError(n)&&n.response?.status===404&&typeof n.response?.data?.message=="string"&&n.response.data.message.includes("User not found"))return!1;throw n}}async function Bb(e,t){try{let n={message:"I am a Truebit User"};if(!t)throw Error("Secret.json does not exists");let a=t.privateKey,r=t.address,i=ls.createSignedBody(n,a,r);return(await(await po()).get(`user/${e}`,{headers:{"truebit-auth":JSON.stringify(i)}})).data}catch(n){if(qp.isAxiosError(n)&&n.response?.status===401&&n.response?.data.message.includes("Entitlement Validation Error")||qp.isAxiosError(n)&&n.response?.status==404&&n.response?.data.message&&n.response?.data.message.includes("User not found"))return null;throw qp.isAxiosError(n)?n.response?Error(`The server responding with an error -> ${n.response.data.message||n.response.status+" - "+n.response.statusText}`):n.request?Error(`The server is not responding -> ${n.message}`):Error(`There was an error in the communication with the server -> ${n.message}`):Error(typeof n=="string"?`There was an error in the communication with the server -> ${n}`:"There was an error in the communication with the server.")}}async function yY(e){try{return await(await po()).post("user/register",e)}catch(t){throw qp.isAxiosError(t)?t.response?Error(`The server responding with an error -> ${t.response.data.message||t.response.status+" - "+t.response.statusText}`):t.request?Error(`The server is not responding -> ${t.message}`):Error(`There was an error in the communication with the server -> ${t.message}`):Error(typeof t=="string"?`There was an error in the communication with the server -> ${t}`:"There was an error in the communication with the server.")}}async function Fke(){let e=Tt("blockchainEnv"),t=dn(e),n="";try{await cY(async()=>{n=qke();let a=xw.keccak256(xw.toUtf8Bytes(n));return await t.authorization.getPayerAddress(a)===uY},{delay:500,maxTry:5,until:a=>a===!0})}catch(a){throw lY(a)?Error("Attempts to generate unique Api Key for the user exhausted."):a}return n}async function jke(){let e=Tt("blockchainEnv"),t=dn(e),n="";try{await cY(async()=>(n=Bke(4).toString("hex"),await t.taskRegistry.getNamespaceOwner(n)===uY),{delay:500,maxTry:5,until:a=>a===!0})}catch(a){throw lY(a)?Error("Attempts to generate unique namespace for the user exhausted."):a}return n}function gY(e){e.fullNameAnswer="",e.emailAddressAnswer="",e.companyNameAnswer="",e.jobPositionAnswer="",e.eulaAnswer="",e.confirmRegistration=""}import zke from"ora";import*as qb from"os";async function vY(e,t,n){let a=Wa(),r=a!==null,i=0,s,f=Hke({input:process.stdin,output:process.stdout,terminal:!0});switch(r&&(mY(a.address)?i=1:(s=await Bb(a.address,a),s?i=2:i=3)),i){case 1:console.log("The wallet set in the configuration must be a valid ethereum address. (ENS not supported yet)");break;case 2:console.log(Jt.SETUP_STEP1_SCENARIO1_P2(s));break;case 3:{console.log(Jt.SETUP_STEP2_SCENARIO3_P1),console.log();let l={user_ip:e,date_time:Mn(),os_version:qb.type+"_"+qb.release,node_version:process.version,cli_version:t};await n.sendEventToMixpanel("user_registration_begin",l);let d={confirmRegistration:"",fullNameAnswer:"",emailAddressAnswer:"",companyNameAnswer:"",jobPositionAnswer:"",eulaAnswer:""};try{for(;d.confirmRegistration!="Y";){for(d.fullNameAnswer=(await f.question(kf.bold(" 1. Full Name: "))).trim();d.fullNameAnswer==="";)console.log("Your full name is required. Please provide your first and last name to proceed."),d.fullNameAnswer=(await f.question(kf.bold(" 1. Full Name: "))).trim();for(d.emailAddressAnswer=(await f.question(kf.bold(" 2. Email Address: "))).trim();!await pY(d.emailAddressAnswer);)d.emailAddressAnswer=(await f.question(kf.bold(" 2. Email Address: "))).trim();for(d.companyNameAnswer=(await f.question(kf.bold(" 3. Company Name: "))).trim(),d.jobPositionAnswer=(await f.question(kf.bold(" 4. Job Position: "))).trim();!gd(d.eulaAnswer);)d.eulaAnswer=(await f.question(kf.bold(` 5. Accept EULA? [Y|N] (${Jt.EULA_TERMS_LINK}): `))).toUpperCase();if(d.eulaAnswer=="N"){console.log(Jt.EULA_REGISTRATION_NO_ACCEPTED);break}for(;!gd(d.confirmRegistration);)console.log(`
227
+ Couldn't push api credentials to remote server: ${f}`}}import{inspect as eOe}from"util";import ua from"ora";import{v4 as tOe}from"uuid";import{ethers as Yb}from"ethers";var oY={name:"@truebit/cli",version:"1.120.0-beta.209",private:!1,description:"truebit-cli is a basic command line that allows interaction between users and truebit nextgen node.",author:{name:"Truebit Co.",url:"https://truebit.io/"},license:"https://truebit.io/terms/",repository:{type:"git",url:"https://github.com/TruebitProtocol"},homepage:"https://truebit.io/",main:"build/index.mjs",module:"build/index.mjs",types:"build/types/index.d.ts",type:"module",scripts:{prebuild:"rimraf build logs","prebuild:dev":"rimraf build logs","build:dev":"tsc && chmod +x build/index.mjs",build:"NODE_ENV=production node esbuild.config.mjs && chmod +x build/index.mjs",dev:"export NODE_ENV=development && npx nodemon",test:"vitest run --passWithNoTests tests/"},dependencies:{axios:"1.12.1",chalk:"5.6.2",colors:"1.4.0",commander:"14.0.1",ethers:"6.15.0",figlet:"1.9.1","openapi-enforcer":"1.23.0",ora:"8.2.0","public-ip":"7.0.1","ts-retry":"6.0.0",uuid:"13.0.0"},bin:{truebit:"build/index.mjs"},files:["build"],devDependencies:{"@types/figlet":"1.7.0","@vitest/coverage-v8":"3.2.4",esbuild:"^0.25.9",typescript:"5.9.2",vitest:"3.2.4"},engines:{node:">=22.13.0"}};import{createInterface as Hke}from"node:readline/promises";import kf from"chalk";import qp from"axios";import{ethers as xw}from"ethers";import{randomBytes as Bke}from"crypto";import{v4 as qke}from"uuid";import{ethers as Db}from"ethers";async function dY(e,t=Tt("blockchainEnv")){Lp(e);let n=dn(t),a=Db.keccak256(Db.toUtf8Bytes(e));return await n.authorization.registerAuthorization(a),a}async function Lb(e,t,n=Tt("blockchainEnv"),a=Tt("address")){Lp(e);let r=dn(n),i=await r.authorization.getEIP712Domain(),s=await r.authorization.nonces(a),f=Math.floor(Date.now()/1e3)+3600,l={RegisterMeta:[{name:"user",type:"address"},{name:"apiKeyHash",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},d=Db.keccak256(Db.toUtf8Bytes(e)),p={user:a,apiKeyHash:d,nonce:Number(s),deadline:f},b=await r.utils.signMeta(i,l,p);return(await VK(a,d,f,b,t)).status==201?d:null}import{isTooManyTries as lY,retryAsync as cY}from"ts-retry";var uY="0x0000000000000000000000000000000000000000";async function pY(e){let t=!0;return e===""?(t=!1,console.log("An email address is required. Please provide your email address to proceed.")):new RegExp(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(e)?await Uke(e)&&(t=!1,console.log("The provided email address is already in use. Please enter a different email address.")):(t=!1,console.log("The email address provided is not valid. Please try again.")),t}function gd(e){return e==="Y"||e==="N"}function mY(e){return!xw.isAddress(e)||e.length!==42||!e.startsWith("0x")}async function hY(){let e=await Fke();try{if(!await Lb(e,!0))throw Error("The API key could not been registered.")}catch(t){let n=t.message;if(n)throw Error(`There was an error registering the API key -> ${n}`)}return e}async function bY(){let e=await jke();try{if(!await kb(e,!0))throw Error("The namespace could not been registered.")}catch(t){let n=t.message,a=n?n.match(/execution reverted: "(.*?)" /)?.[1]:null;if(a)throw Error(`There was an error registering the namespace -> ${a}`);if(n)throw Error(`There was an error registering the namespace -> ${n}`)}return e}async function Uke(e){let t=await po();try{return(await t.get(`userexistence/${e}`)).data===!0}catch(n){if(qp.isAxiosError(n)&&n.response?.status===404&&typeof n.response?.data?.message=="string"&&n.response.data.message.includes("User not found"))return!1;throw n}}async function Bb(e,t){try{let n={message:"I am a Truebit User"};if(!t)throw Error("Secret.json does not exists");let a=t.privateKey,r=t.address,i=ls.createSignedBody(n,a,r);return(await(await po()).get(`user/${e}`,{headers:{"truebit-auth":JSON.stringify(i)}})).data}catch(n){if(qp.isAxiosError(n)&&n.response?.status===401&&n.response?.data.message.includes("Entitlement Validation Error")||qp.isAxiosError(n)&&n.response?.status==404&&n.response?.data.message&&n.response?.data.message.includes("User not found"))return null;throw qp.isAxiosError(n)?n.response?Error(`The server responding with an error -> ${n.response.data.message||n.response.status+" - "+n.response.statusText}`):n.request?Error(`The server is not responding -> ${n.message}`):Error(`There was an error in the communication with the server -> ${n.message}`):Error(typeof n=="string"?`There was an error in the communication with the server -> ${n}`:"There was an error in the communication with the server.")}}async function yY(e){try{return await(await po()).post("user/register",e)}catch(t){throw qp.isAxiosError(t)?t.response?Error(`The server responding with an error -> ${t.response.data.message||t.response.status+" - "+t.response.statusText}`):t.request?Error(`The server is not responding -> ${t.message}`):Error(`There was an error in the communication with the server -> ${t.message}`):Error(typeof t=="string"?`There was an error in the communication with the server -> ${t}`:"There was an error in the communication with the server.")}}async function Fke(){let e=Tt("blockchainEnv"),t=dn(e),n="";try{await cY(async()=>{n=qke();let a=xw.keccak256(xw.toUtf8Bytes(n));return await t.authorization.getPayerAddress(a)===uY},{delay:500,maxTry:5,until:a=>a===!0})}catch(a){throw lY(a)?Error("Attempts to generate unique Api Key for the user exhausted."):a}return n}async function jke(){let e=Tt("blockchainEnv"),t=dn(e),n="";try{await cY(async()=>(n=Bke(4).toString("hex"),await t.taskRegistry.getNamespaceOwner(n)===uY),{delay:500,maxTry:5,until:a=>a===!0})}catch(a){throw lY(a)?Error("Attempts to generate unique namespace for the user exhausted."):a}return n}function gY(e){e.fullNameAnswer="",e.emailAddressAnswer="",e.companyNameAnswer="",e.jobPositionAnswer="",e.eulaAnswer="",e.confirmRegistration=""}import zke from"ora";import*as qb from"os";async function vY(e,t,n){let a=Wa(),r=a!==null,i=0,s,f=Hke({input:process.stdin,output:process.stdout,terminal:!0});switch(r&&(mY(a.address)?i=1:(s=await Bb(a.address,a),s?i=2:i=3)),i){case 1:console.log("The wallet set in the configuration must be a valid ethereum address. (ENS not supported yet)");break;case 2:console.log(Jt.SETUP_STEP1_SCENARIO1_P2(s));break;case 3:{console.log(Jt.SETUP_STEP2_SCENARIO3_P1),console.log();let l={user_ip:e,date_time:Mn(),os_version:qb.type+"_"+qb.release,node_version:process.version,cli_version:t};await n.sendEventToMixpanel("user_registration_begin",l);let d={confirmRegistration:"",fullNameAnswer:"",emailAddressAnswer:"",companyNameAnswer:"",jobPositionAnswer:"",eulaAnswer:""};try{for(;d.confirmRegistration!="Y";){for(d.fullNameAnswer=(await f.question(kf.bold(" 1. Full Name: "))).trim();d.fullNameAnswer==="";)console.log("Your full name is required. Please provide your first and last name to proceed."),d.fullNameAnswer=(await f.question(kf.bold(" 1. Full Name: "))).trim();for(d.emailAddressAnswer=(await f.question(kf.bold(" 2. Email Address: "))).trim();!await pY(d.emailAddressAnswer);)d.emailAddressAnswer=(await f.question(kf.bold(" 2. Email Address: "))).trim();for(d.companyNameAnswer=(await f.question(kf.bold(" 3. Company Name: "))).trim(),d.jobPositionAnswer=(await f.question(kf.bold(" 4. Job Position: "))).trim();!gd(d.eulaAnswer);)d.eulaAnswer=(await f.question(kf.bold(` 5. Accept EULA? [Y|N] (${Jt.EULA_TERMS_LINK}): `))).toUpperCase();if(d.eulaAnswer=="N"){console.log(Jt.EULA_REGISTRATION_NO_ACCEPTED);break}for(;!gd(d.confirmRegistration);)console.log(`
228
228
  Is the information provided above correct?`),d.confirmRegistration=(await f.question(kf.bold("Press [Y] to confirm or [N] to edit: "))).toUpperCase();d.confirmRegistration=="N"&&(console.log(`
229
229
  Please provide the following information:`),gY(d))}}catch(w){if(w.name==="AbortError"||w.message.includes("Ctrl+C")){let T=w.message,x=l;x.error_details=T,x.date_time=Mn();let k={fullname:d.fullNameAnswer,email:d.emailAddressAnswer,company:d.companyNameAnswer,role:d.jobPositionAnswer};x.user_info=JSON.stringify(k),await n.sendEventToMixpanel("user_registration_failed",x),process.exit(0)}}if(d.eulaAnswer=="N")break;let p=l;console.log(),console.log("By completing registration, you'll be automatically subscribed to our newsletter."),console.log("To opt-out, please follow the steps described in our documentation portal."),console.log();let b=zke({text:kf.bold("... registering your account."),stream:process.stdout}).start();try{let w=await bY(),T=await hY(),x={name:d.fullNameAnswer,email:d.emailAddressAnswer,walletAddress:a?.address,company:d.companyNameAnswer,jobDescription:d.jobPositionAnswer,EULA:ls.createSignedBody({ip:await xb(),date:new Date().toISOString()},a.privateKey),defaultNamespace:w,defaultApiKey:T};await yY(x),b.stop(),console.log(Jt.SETUP_STEP2_SCENARIO3_P2(d,a.address,w,T)),p.distinct_id=x.walletAddress,p.date_time=Mn(),p.fullname=x.name,p.email=x.email,p.company=x.company,p.role=x.jobDescription,p.namespace=x.defaultNamespace,p.api_key=T,p.wallet_address=x.walletAddress,await n.sendEventToMixpanel("user_registration_success",p),await n.registerUserMixpanel(p.wallet_address,Vke(p))}catch(w){b.stop();let T=w.message,x=l;x.error_details=T,x.date_time=Mn();let k={fullname:d.fullNameAnswer,email:d.emailAddressAnswer,company:d.companyNameAnswer,role:d.jobPositionAnswer};x.user_info=JSON.stringify(k),await n.sendEventToMixpanel("user_registration_failed",x);let D=T?T.match(/CreateUserValidation - (.*?.*)/)?.[1]:null;if(D)throw Error(D);if(T.includes("Sender doesn't have enough funds to send tx"))throw Error("We are currently experiencing technical difficulties. Please try again later.");console.error(Jt.SETUP_STEP2_UNHANDLED_ERROR),process.exit(1)}finally{b.clear()}break}default:throw Error("An unexpected error occurred.")}f.close()}function Vke(e){return{apiKey:e.api_key,name:e.fullname,email:e.email,ip:e.user_ip,company:e.company,role:e.role,namespace:e.namespace,walletAddress:e.wallet_address}}import{setDefaultAutoSelectFamily as nOe}from"node:net";import Wke from"chalk";import{createInterface as Gke}from"node:readline/promises";import*as Ub from"os";async function xY(e,t,n){let a=Wa(),r=a!==null,i=0;switch(r?r&&!a.eula?i=2:i=3:i=1,i){case 1:case 2:{let s=Gke({input:process.stdin,output:process.stdout,terminal:!0}),f="",l={user_ip:e,date_time:Mn(),os_version:Ub.type+"_"+Ub.release,node_version:process.version,cli_version:t};for(console.log(Jt.EULA_INSTALLATION);!gd(f);)f=(await s.question(Wke.bold(`
230
230
  Have you read, and do you accept the Terms of Use? [Y|N]: `))).toUpperCase(),await n.sendEventToMixpanel("TOS_shown",l);if(f=="N")throw l.date_time=Mn(),await n.sendEventToMixpanel("TOS_rejected",l),Jt.EULA_INSTALLATION_NO_ACCEPTED;l.date_time=Mn(),await n.sendEventToMixpanel("TOS_accepted",l);let d=Math.round(new Date().getTime()).toString();if(i===1){let p={...oc(),eula:d};WG(p)}else i===2&&_p({eula:d});s.close()}break;case 3:default:break}}async function Mi(e=!1){let t=Wa(),n=t!==null,a=null,r=0;switch(n?n&&(!t.privateKey||!t.address)?r=2:(a=await Bb(t.address,t),a?r=4:r=3):r=1,r){case 1:case 2:case 3:console.log(Jt.USER_NO_REGISTERED),process.exit(1);break;case 4:e&&console.log(`You are logged in as: ${a?.name} - ${a?.email}`);break}}import{createInterface as Kke}from"node:readline/promises";import Yke from"chalk";async function _Y(){console.log(Yke.bold(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@truebit/cli",
3
- "version": "1.120.0-beta.208",
3
+ "version": "1.120.0-beta.209",
4
4
  "private": false,
5
5
  "description": "truebit-cli is a basic command line that allows interaction between users and truebit nextgen node.",
6
6
  "author": {
@@ -54,5 +54,5 @@
54
54
  "engines": {
55
55
  "node": ">=22.13.0"
56
56
  },
57
- "gitHead": "7affe81de632986b15fb67ee380765ed478da39a"
57
+ "gitHead": "8872ca41da1a71aa8afb09f0b7c6ca6aae7054f0"
58
58
  }