@truebit/cli 1.120.0-beta.215 → 1.120.0-beta.216

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
@@ -223,7 +223,7 @@ API Task response`)}
223
223
  `,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 oke}from"ethers";function hK(e){return/^[a-f0-9]{64}$/gi.test(e)}function yK(e){try{new oke(e)}catch{return!1}return!0}var xc=e=>{let t=e.split("_");return!!hK(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 dke}from"ethers";import mw from"axios";async function gK(e,t,n,a,r,i){let s={user:e,namespace:t,nonce:BigInt(n),deadline:a,signatureMeta:r};try{let f=await bo(),l={...s};return l.nonce=String(s.nonce),await f.post("user/relayer/namespace",l,{params:{fromSetup:i}})}catch(f){throw mw.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 bo()).post("user/relayer/auth",i,{params:{fromSetup:r}})}catch(s){throw mw.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 xK(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 bo(),d={...f};return d.nonce=String(f.nonce),await l.post("user/relayer/task",d)}catch(l){throw mw.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 Ch(e,t,n=null,a=Tt("blockchainEnv")){Ea(e,"Namespace");let r,i=ln(a,at.AVAX),s=Tt("address");if(!s)throw`Please provide an address property in '${ms()}/.truebit/secret.json'`;return n?r=await i.taskRegistry.registerTaskNamespace(e):r=await lke(s,e,i,t),r}async function lke(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:dke.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 gK(e,t,f.nonce,f.deadline,l,a)).status==201}async function _K(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 xK(e,t,n,a,f.nonce,f.deadline,l)).status==201}async function wK(e){return await(await $0()).post("api/filesystem/push",bs({taskId:e})).catch(D0)}async function TK(e,t){let n=Tt("blockchainEnv");return await ln(n,at.AVAX).taskRegistry.getLatestVersion(e,t)}async function AK(e,t,n,a=null){let r=Tt("blockchainEnv"),i=ln(r,at.AVAX),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 '${ms()}/.truebit/secret.json'`);s=await _K(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 SK(e,t,n,a,r){if(!xc(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 wK(n),await AK({taskId:n,meta:a||"",active:!0},e,t,r),i=await TK(e,t)}catch(s){if(s instanceof Error)throw s;if(typeof s=="string")throw new Error(s)}return i}async function IK(e,t,n){let a=Tt("blockchainEnv"),r=ln(a,at.AVAX),i=await r.taskRegistry.getLatestVersion(e,t);return await r.taskRegistry.setTaskLabel(e,t,i,n)}import*as Mh from"fs";import*as CK from"path";var MK=async(e,t,n)=>{if(console.log("Executing the function Task"),!xc(t))throw"Invalid task id";let a={status:"",result:""},r=await $0(),i=await r.post("api/execution/",bs({taskId:t,input:n})).catch(D0),s=i.data.executionId;return console.log(`Execution Id: ${s}`),i.data.payload?(EK(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"&&(EK(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 EK(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=CK.join(process.cwd(),"config.json");try{let s=Mh.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),Mh.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 PK(e){try{let n=await(await $0()).post("api/instrumentation",bs({taskId:`${e}`})).catch(D0);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:
224
224
  ${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 kK from"readline";import{ethers as cke}from"ethers";async function RK(){let e=Ka(),t=e!==null,n=kK.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(Qt.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:hh(),console.log(Qt.SETUP_STEP1_SCENARIO1_P1);break;case 2:{hh();let i=cke.Wallet.createRandom(),s=i.privateKey,f=i.address;Cp({privateKey:s,address:f}),console.log(`
225
225
  Setting up your new wallet...`),console.log(Qt.SETUP_STEP1_SCENARIO2(f));break}case 3:hh(),console.log(Qt.SETUP_STEP1_SCENARIO3),process.exit(1);break;default:console.log("An unexpected error occurred.");break}n.close()}async function OK(e){try{console.log("Fetching execution status...");let n=await(await $0()).get(`api/execution/${e}`).catch(D0);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 NK=mt(J_(),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")}}},Ph=class extends Bp{tokens=["accessKey","secretKey"];constructor(t){super(),this.parse(this.tokens,t)}authHeaders(t){return NK.default.sign(t,{accessKeyId:this.authInputs.accessKey,secretAccessKey:this.authInputs.secretKey}).headers||{}}},kh=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}`)}`}}},Rh=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 bw=(e,t)=>{switch(e){case Ei.AWS_SIGNATURE:return new Ph(t);case Ei.BASIC_AUTH:return new kh(t);case Ei.CUSTOM_HEADER:return new Rh(t);default:throw new Error(`Invalid authentication method specified. Should be one of <${Object.values(Ei)}>`)}};import pke from"chalk";import{ethers as mke}from"ethers";async function $K(e,t,n,a,r,i,s){console.log("Deploying the API Authentication Credentials");try{if(!yK(i))throw"Invalid private key provided";if(!mke.isAddress(s))throw"Invalid address provided";if(bw(a,r),!xc(e))throw"Invalid taskId";await(await $0()).post("api/api-credentials",bs({taskId:e,namespace:t,taskName:n,authString:r,method:a})).catch(D0),console.log("The credentials were deployed "+pke.green("Successfully"))}catch(f){throw`There was an Error deploying credentials:
226
- Couldn't push api credentials to remote server: ${f}`}}import{inspect as RRe}from"util";import ba from"ora";import{v4 as ORe}from"uuid";import{ethers as Wh}from"ethers";var DK={name:"@truebit/cli",version:"1.120.0-beta.215",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.2",chalk:"5.6.2",colors:"1.4.0",commander:"14.0.1",ethers:"6.15.0",figlet:"1.9.3","openapi-enforcer":"1.23.0",ora:"9.0.0","public-ip":"8.0.0","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.10",typescript:"5.9.3",vitest:"3.2.4"},engines:{node:">=22.13.0"}};import{createInterface as _ke}from"node:readline/promises";import Of from"chalk";import qp from"axios";import{ethers as hw}from"ethers";import{randomBytes as hke}from"crypto";import{v4 as yke}from"uuid";import{ethers as Oh}from"ethers";async function LK(e,t=Tt("blockchainEnv")){Lp(e);let n=ln(t,at.AVAX),a=Oh.keccak256(Oh.toUtf8Bytes(e));return await n.authorization.registerAuthorization(a),a}async function Nh(e,t,n=Tt("blockchainEnv"),a=Tt("address")){Lp(e);let r=ln(n,at.AVAX),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=Oh.keccak256(Oh.toUtf8Bytes(e)),p={user:a,apiKeyHash:d,nonce:Number(s),deadline:f},h=await r.utils.signMeta(i,l,p);return(await vK(a,d,f,h,t)).status==201?d:null}import{isTooManyTries as BK,retryAsync as qK}from"ts-retry";var UK="0x0000000000000000000000000000000000000000";async function FK(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 gke(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 vd(e){return e==="Y"||e==="N"}function jK(e){return!hw.isAddress(e)||e.length!==42||!e.startsWith("0x")}async function HK(){let e=await vke();try{if(!await Nh(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 zK(){let e=await xke();try{if(!await Ch(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 gke(e){let t=await bo();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 $h(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=ps.createSignedBody(n,a,r);return(await(await bo()).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 VK(e){try{return await(await bo()).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 vke(){let e=Tt("blockchainEnv"),t=ln(e,at.AVAX),n="";try{await qK(async()=>{n=yke();let a=hw.keccak256(hw.toUtf8Bytes(n));return await t.authorization.getPayerAddress(a)===UK},{delay:500,maxTry:5,until:a=>a===!0})}catch(a){throw BK(a)?Error("Attempts to generate unique Api Key for the user exhausted."):a}return n}async function xke(){let e=Tt("blockchainEnv"),t=ln(e,at.AVAX),n="";try{await qK(async()=>(n=hke(4).toString("hex"),await t.taskRegistry.getNamespaceOwner(n)===UK),{delay:500,maxTry:5,until:a=>a===!0})}catch(a){throw BK(a)?Error("Attempts to generate unique namespace for the user exhausted."):a}return n}function WK(e){e.fullNameAnswer="",e.emailAddressAnswer="",e.companyNameAnswer="",e.jobPositionAnswer="",e.eulaAnswer="",e.confirmRegistration=""}import wke from"ora";import*as Dh from"os";async function GK(e,t,n){let a=Ka(),r=a!==null,i=0,s,f=_ke({input:process.stdin,output:process.stdout,terminal:!0});switch(r&&(jK(a.address)?i=1:(s=await $h(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(Qt.SETUP_STEP1_SCENARIO1_P2(s));break;case 3:{console.log(Qt.SETUP_STEP2_SCENARIO3_P1),console.log();let l={user_ip:e,date_time:Mn(),os_version:Dh.type+"_"+Dh.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(Of.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(Of.bold(" 1. Full Name: "))).trim();for(d.emailAddressAnswer=(await f.question(Of.bold(" 2. Email Address: "))).trim();!await FK(d.emailAddressAnswer);)d.emailAddressAnswer=(await f.question(Of.bold(" 2. Email Address: "))).trim();for(d.companyNameAnswer=(await f.question(Of.bold(" 3. Company Name: "))).trim(),d.jobPositionAnswer=(await f.question(Of.bold(" 4. Job Position: "))).trim();!vd(d.eulaAnswer);)d.eulaAnswer=(await f.question(Of.bold(` 5. Accept EULA? [Y|N] (${Qt.EULA_TERMS_LINK}): `))).toUpperCase();if(d.eulaAnswer=="N"){console.log(Qt.EULA_REGISTRATION_NO_ACCEPTED);break}for(;!vd(d.confirmRegistration);)console.log(`
226
+ Couldn't push api credentials to remote server: ${f}`}}import{inspect as RRe}from"util";import ba from"ora";import{v4 as ORe}from"uuid";import{ethers as Wh}from"ethers";var DK={name:"@truebit/cli",version:"1.120.0-beta.216",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.2",chalk:"5.6.2",colors:"1.4.0",commander:"14.0.1",ethers:"6.15.0",figlet:"1.9.3","openapi-enforcer":"1.23.0",ora:"9.0.0","public-ip":"8.0.0","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.10",typescript:"5.9.3",vitest:"3.2.4"},engines:{node:">=22.13.0"}};import{createInterface as _ke}from"node:readline/promises";import Of from"chalk";import qp from"axios";import{ethers as hw}from"ethers";import{randomBytes as hke}from"crypto";import{v4 as yke}from"uuid";import{ethers as Oh}from"ethers";async function LK(e,t=Tt("blockchainEnv")){Lp(e);let n=ln(t,at.AVAX),a=Oh.keccak256(Oh.toUtf8Bytes(e));return await n.authorization.registerAuthorization(a),a}async function Nh(e,t,n=Tt("blockchainEnv"),a=Tt("address")){Lp(e);let r=ln(n,at.AVAX),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=Oh.keccak256(Oh.toUtf8Bytes(e)),p={user:a,apiKeyHash:d,nonce:Number(s),deadline:f},h=await r.utils.signMeta(i,l,p);return(await vK(a,d,f,h,t)).status==201?d:null}import{isTooManyTries as BK,retryAsync as qK}from"ts-retry";var UK="0x0000000000000000000000000000000000000000";async function FK(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 gke(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 vd(e){return e==="Y"||e==="N"}function jK(e){return!hw.isAddress(e)||e.length!==42||!e.startsWith("0x")}async function HK(){let e=await vke();try{if(!await Nh(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 zK(){let e=await xke();try{if(!await Ch(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 gke(e){let t=await bo();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 $h(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=ps.createSignedBody(n,a,r);return(await(await bo()).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 VK(e){try{return await(await bo()).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 vke(){let e=Tt("blockchainEnv"),t=ln(e,at.AVAX),n="";try{await qK(async()=>{n=yke();let a=hw.keccak256(hw.toUtf8Bytes(n));return await t.authorization.getPayerAddress(a)===UK},{delay:500,maxTry:5,until:a=>a===!0})}catch(a){throw BK(a)?Error("Attempts to generate unique Api Key for the user exhausted."):a}return n}async function xke(){let e=Tt("blockchainEnv"),t=ln(e,at.AVAX),n="";try{await qK(async()=>(n=hke(4).toString("hex"),await t.taskRegistry.getNamespaceOwner(n)===UK),{delay:500,maxTry:5,until:a=>a===!0})}catch(a){throw BK(a)?Error("Attempts to generate unique namespace for the user exhausted."):a}return n}function WK(e){e.fullNameAnswer="",e.emailAddressAnswer="",e.companyNameAnswer="",e.jobPositionAnswer="",e.eulaAnswer="",e.confirmRegistration=""}import wke from"ora";import*as Dh from"os";async function GK(e,t,n){let a=Ka(),r=a!==null,i=0,s,f=_ke({input:process.stdin,output:process.stdout,terminal:!0});switch(r&&(jK(a.address)?i=1:(s=await $h(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(Qt.SETUP_STEP1_SCENARIO1_P2(s));break;case 3:{console.log(Qt.SETUP_STEP2_SCENARIO3_P1),console.log();let l={user_ip:e,date_time:Mn(),os_version:Dh.type+"_"+Dh.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(Of.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(Of.bold(" 1. Full Name: "))).trim();for(d.emailAddressAnswer=(await f.question(Of.bold(" 2. Email Address: "))).trim();!await FK(d.emailAddressAnswer);)d.emailAddressAnswer=(await f.question(Of.bold(" 2. Email Address: "))).trim();for(d.companyNameAnswer=(await f.question(Of.bold(" 3. Company Name: "))).trim(),d.jobPositionAnswer=(await f.question(Of.bold(" 4. Job Position: "))).trim();!vd(d.eulaAnswer);)d.eulaAnswer=(await f.question(Of.bold(` 5. Accept EULA? [Y|N] (${Qt.EULA_TERMS_LINK}): `))).toUpperCase();if(d.eulaAnswer=="N"){console.log(Qt.EULA_REGISTRATION_NO_ACCEPTED);break}for(;!vd(d.confirmRegistration);)console.log(`
227
227
  Is the information provided above correct?`),d.confirmRegistration=(await f.question(Of.bold("Press [Y] to confirm or [N] to edit: "))).toUpperCase();d.confirmRegistration=="N"&&(console.log(`
228
228
  Please provide the following information:`),WK(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 h=wke({text:Of.bold("... registering your account."),stream:process.stdout}).start();try{let w=await zK(),T=await HK(),x={name:d.fullNameAnswer,email:d.emailAddressAnswer,walletAddress:a?.address,company:d.companyNameAnswer,jobDescription:d.jobPositionAnswer,EULA:ps.createSignedBody({ip:await yh(),date:new Date().toISOString()},a.privateKey),defaultNamespace:w,defaultApiKey:T};await VK(x),h.stop(),console.log(Qt.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,Tke(p))}catch(w){h.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(Qt.SETUP_STEP2_UNHANDLED_ERROR),process.exit(1)}finally{h.clear()}break}default:throw Error("An unexpected error occurred.")}f.close()}function Tke(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 NRe}from"node:net";import Ake from"chalk";import{createInterface as Ske}from"node:readline/promises";import*as Lh from"os";async function KK(e,t,n){let a=Ka(),r=a!==null,i=0;switch(r?r&&!a.eula?i=2:i=3:i=1,i){case 1:case 2:{let s=Ske({input:process.stdin,output:process.stdout,terminal:!0}),f="",l={user_ip:e,date_time:Mn(),os_version:Lh.type+"_"+Lh.release,node_version:process.version,cli_version:t};for(console.log(Qt.EULA_INSTALLATION);!vd(f);)f=(await s.question(Ake.bold(`
229
229
  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),Qt.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={...dc(),eula:d};wG(p)}else i===2&&Cp({eula:d});s.close()}break;case 3:default:break}}async function Ci(e=!1){let t=Ka(),n=t!==null,a=null,r=0;switch(n?n&&(!t.privateKey||!t.address)?r=2:(a=await $h(t.address,t),a?r=4:r=3):r=1,r){case 1:case 2:case 3:console.log(Qt.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 Ike}from"node:readline/promises";import Eke from"chalk";async function YK(){console.log(Eke.bold(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@truebit/cli",
3
- "version": "1.120.0-beta.215",
3
+ "version": "1.120.0-beta.216",
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": "32ccbe4555c4ba3ff7e282e22eac8de355b30602"
57
+ "gitHead": "fb4fa8484cfb6ff41776459a8a202974a0cab408"
58
58
  }