ixo-oracles-cli 1.0.4 → 1.0.6

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/License.txt ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 IXO World
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -220,4 +220,4 @@ For issues and questions:
220
220
 
221
221
  ## License
222
222
 
223
- ISC
223
+ This project is licensed under the Apache License 2.0. See [License.txt](License.txt) for details.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{cancel as fe,intro as nr,isCancel as it,log as W,outro as or,select as nt,spinner as sr}from"@clack/prompts";import b from"process";var _=class{commands;constructor(){this.commands=new Map}register(e){this.commands.set(e.name,e)}get(e){return this.commands.get(e)}getAll(){return Array.from(this.commands.values())}getCommandOptions(){return this.getAll().map(e=>({value:e.name,label:e.name,hint:e.description}))}};import*as p from"@clack/prompts";import{select as at}from"@clack/prompts";import{z as re}from"zod";var j=async r=>{let e=await at({message:"Select network: (default: devnet)",options:[{value:"mainnet",label:"Mainnet"},{value:"testnet",label:"Testnet"},{value:"devnet",label:"Devnet"}],initialValue:"devnet",maxItems:1});return r.addValue("network",e),e},we={mainnet:"did:ixo:entity:2f22535f8b179a51d77a0e302e68d35d",testnet:"did:ixo:entity:3d079ebc0b332aad3305bb4a51c72edb",devnet:"did:ixo:entity:2f22535f8b179a51d77a0e302e68d35d"},C={devnet:"https://devmx.ixo.earth",testnet:"https://testmx.ixo.earth",mainnet:"https://mx.ixo.earth"},k={devnet:"https://rooms.bot.devmx.ixo.earth",testnet:"https://rooms.bot.testmx.ixo.earth",mainnet:"https://rooms.bot.mx.ixo.earth"};var xe={devnet:"https://ixo-portal.vercel.app",testnet:"https://ixo-portal.vercel.app",mainnet:"https://ixo-portal.vercel.app"},I={mainnet:"https://impacthub.ixo.world/rpc/",testnet:"https://testnet.ixo.earth/rpc/",devnet:"https://devnet.ixo.earth/rpc/"},v=(r,e="This field is required")=>{let i=re.string().min(1,e).safeParse(r);if(!i.success)return i.error.message},ie=(r,e="This url is required or a valid URL")=>{let i=re.url(e).safeParse(r);if(!i.success)return i.error.message},Ce=(r,e="This number is required")=>{let i=re.number().min(1,e).safeParse(r);if(!i.success)return i.error.message};import{isCancel as $t,log as y,spinner as Xt,text as Bt}from"@clack/prompts";import{customMessages as Je,ixo as E,utils as me}from"@ixo/impactxclient-sdk";import{utils as de}from"@ixo/impactxclient-sdk";import{createMatrixApiClient as Wt}from"@ixo/matrixclient-sdk";import{sha256 as Et}from"@cosmjs/crypto";import{encrypt as St}from"eciesjs";import{ClientEvent as At,createClient as ae}from"matrix-js-sdk";import bt from"md5";var F=new Map;function ct(r){return F.get(r)instanceof Uint8Array}function lt(r){return F.get(r)}function ne(){F.clear()}async function ve({keys:r}){let e=Object.keys(r),t=e.find(ct);if(console.info("[] getSecretStorageKey",r,e,t),!t)return null;let i=lt(t);return[t,i]}function Re(r,e,t){F.set(r,t)}import{Bip39 as be,EnglishMnemonic as Pe,Secp256k1 as oe,sha256 as pt,Slip10 as Oe,Slip10Curve as Ie,stringToPath as Te}from"@cosmjs/crypto";import{DirectSecp256k1HdWallet as gt}from"@cosmjs/proto-signing";import{createQueryClient as Ne,createSigningClient as ut,customMessages as ft,ixo as ht,utils as yt}from"@ixo/impactxclient-sdk";import{createCipheriv as wt,randomBytes as xt}from"crypto";import{createQueryClient as xr,createRegistry as dt,utils as mt}from"@ixo/impactxclient-sdk";function M(r){try{return mt.proto.fromTimestamp(r).getTime()}catch{return}}var $={BasicAllowance:"/cosmos.feegrant.v1beta1.BasicAllowance",PeriodicAllowance:"/cosmos.feegrant.v1beta1.PeriodicAllowance"};var Ee=r=>{let e=dt();return(r??[]).map(t=>{let i=t.allowance,n=e.decode(i);switch(i.typeUrl){case $.BasicAllowance:return{granter:t.granter,grantee:t.grantee,type:$.BasicAllowance,expiration:n.expiration?M(n.expiration):null,limit:n.spendLimit?.length?n.spendLimit.find(o=>o.denom==="uixo")?.amount:null,msgs:[]};case $.PeriodicAllowance:return{granter:t.granter,grantee:t.grantee,type:$.PeriodicAllowance,expiration:n.basic?.expiration?M(n.basic.expiration):null,limit:n?.periodCanSpend?n?.periodCanSpend?.find(o=>o.denom==="uixo")?.amount:n?.basic?.spendLimit?.length?n?.basic?.spendLimit?.find(o=>o.denom==="uixo")?.amount:null,msgs:[]};default:return{type:i.typeUrl,granter:t.granter,grantee:t.grantee,expiration:n.expiration?M(n.expiration):n.basic?.expiration?M(n.basic.expiration):null,limit:n.spendLimit?.length?n.spendLimit.find(o=>o.denom==="uixo")?.amount:n?.periodCanSpend?n?.periodCanSpend?.find(o=>o.denom==="uixo")?.amount:n?.basic?.spendLimit?.length?n?.basic?.spendLimit?.find(o=>o.denom==="uixo")?.amount:null,msgs:n.allowedMessages}}})},Se=r=>{if(r==null)return!1;let e=typeof r=="object"?M(r):r;return e==null?!0:e<Date.now()},Ae=r=>r==null?!1:(typeof r=="object"?Number(r?.amount??0):typeof r=="string"?Number(r??0):r)<=5e-4;async function se(r,e){if(!e)throw new Error("Network parameter is required but was undefined");console.log(`\u{1F50D} Checking IID document for DID: ${r} on network: ${e}`);let t=I[e];if(!t)throw new Error(`Invalid network: ${e}. Valid networks are: ${Object.keys(I).join(", ")}`);console.log(`\u{1F517} Using RPC URL: ${t}`);try{return!!(await(await Ne(t)).ixo.iid.v1beta1.iidDocument({id:r}))?.iidDocument?.id}catch(i){if(i.message?.includes("did document not found")||i.message?.includes("(22)"))return!1;throw console.error("Error checking IID document:",i),i}}async function Ue(r,e,t){try{let i=await t.getAccounts(),{address:n,pubkey:o}=i[0]??{},s=await Ct(n,e),a=s?.length?Ee(s)?.find(c=>!!c&&!Se(c.expiration)&&!Ae(c.limit))?.granter:void 0,l={typeUrl:"/ixo.iid.v1beta1.MsgCreateIidDocument",value:ht.iid.v1beta1.MsgCreateIidDocument.fromPartial({id:r,verifications:ft.iid.createIidVerificationMethods({did:r,pubkey:o,address:n,controller:r,type:"secp"}),signer:n,controllers:[r]})};await vt({offlineSigner:t,messages:[l],feegrantGranter:a,network:e})}catch(i){throw console.error(i),i}}async function Ct(r,e){try{let t=I[e];if(!t)throw new Error(`Invalid network: ${e}`);return(await(await Ne(t)).cosmos.feegrant.v1beta1.allowances({grantee:r}))?.allowances??[]}catch(t){console.error("queryAddressAllowances::",t.message);return}}var vt=async({offlineSigner:r,messages:e,memo:t="Signing with Mnemonic Demo",feegrantGranter:i,network:n})=>{let o=I[n];if(!o)throw new Error(`Invalid network: ${n}`);let s=await ut(o,r),a=await r.getAccounts(),{address:l}=a[0]??{},c=await s.simulate(l,e,t),f=(c>5e4?c:(e??[]).length*5e5)*1.7,S=Rt(f),w={amount:[{denom:"uixo",amount:String(Math.round(S.average))}],gas:String(Math.round(f)),granter:i},x=await s.signAndBroadcast(l,e,w,t,void 0);if(!!x.code)throw new Error(`Error when broadcasting tx ${x.transactionHash} at height ${x.height}. Code: ${x.code}; Raw log: ${x.rawLog}`)},Rt=r=>{let e={low:.02,average:.035,high:.045},t=r<.01?.01:r;return{low:t*e.low,average:t*e.average,high:t*e.high}},X=r=>new Promise(e=>setTimeout(e,r));function ke(r,e){let t=xt(16),i=wt("aes-256-cbc",Buffer.from(e.padEnd(32)),t),n=i.update(r);return n=Buffer.concat([n,i.final()]),t.toString("hex")+":"+n.toString("hex")}var Me=async r=>{let e=await gt.fromMnemonic(r,{prefix:"ixo"}),t=(await e.getAccounts())[0],i=await be.mnemonicToSeed(new Pe(r)),n=Te("m/44'/118'/0'/0/0"),s=Oe.derivePath(Ie.Secp256k1,i,n).privkey,a=await oe.makeKeypair(s),l=oe.compressPubkey(a.pubkey);return{mnemonic:r,did:yt.did.generateSecpDid(t.address),baseAccount:t,async getAccounts(){return await e.getAccounts()},async signDirect(m,f){return await e.signDirect(m,f)},async sign(m){try{let f=await be.mnemonicToSeed(new Pe(r)),S=Te("m/44'/118'/0'/0/0"),{privkey:w}=Oe.derivePath(Ie.Secp256k1,f,S),x=new Uint8Array(Buffer.from(m,"base64")),Y=pt(x);return(await oe.createSignature(Y,w)).toFixedLength().slice(0,64)}catch(f){throw console.error("Error during signature creation:",f),f}}}};var Pt="/.well-known/matrix/client",ce=async({homeServerUrl:r,username:e,password:t,deviceName:i},n=!1)=>{let o=r,s=e,a=s.match(/^@(.+):(.+\..+)$/);a&&(s=a[1],o=a[2],o=n?o:await Mt(o));try{let l=We(o),c=await l.login("m.login.password",{identifier:{type:"m.id.user",user:Dt(s)},password:t,initial_device_display_name:i});return{accessToken:c.access_token,deviceId:c.device_id,userId:c.user_id,baseUrl:n?o:c?.well_known?.["m.homeserver"]?.base_url||l.baseUrl}}catch(l){let c=l.message;throw c==="Unknown message"&&(c="Please check your credentials"),console.error("mxLogin::",c),new Error(c)}};async function Ot(r){let e=await fetch(`${k[r]}/public-key`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error("Failed to fetch public key for encryption");return await e.json()}function It(r){let e={timestamp:new Date().toISOString(),address:r,service:"matrix",type:"create-account"},t=Buffer.from(JSON.stringify(e)).toString("base64");return{challenge:e,challengeBase64:t}}function Tt(r,e){let t=new Uint8Array(Buffer.from(e,"hex")),i=new Uint8Array(Buffer.from(r,"utf8")),n=St(t,i);return Array.from(n,o=>o.toString(16).padStart(2,"0")).join("")}async function Nt(r,e,t,i,n){let o=await Ot(n),s=Tt(e,o.publicKey),a={address:r,encryptedPassword:s,publicKeyFingerprint:o.fingerprint,secpResult:{signature:t,challenge:i}},l=await fetch(`${k[n]}/user/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!l.ok){let c=await l.json();throw new Error(c.error||"Failed to create user account")}return await l.json()}async function De(r,e,t,i,n){try{let{challengeBase64:o}=It(r),s=await i.sign(o),a=Buffer.from(s).toString("base64");if(!(await Nt(r,e,a,o,n)).success)throw new Error("Failed to create matrix account via API");let c=C[n],m=le(r);return await ce({homeServerUrl:c,username:m,password:e,deviceName:t})}catch(o){throw console.error("mxRegisterWithSecp error:",o),o}}async function Le({homeServerUrl:r,username:e}){let t=We(r);try{return!!await t.isUsernameAvailable(e)}catch{return!1}}function We(r){if(!r)throw new Error("Home server URL is required to instantiate matrix client");return ae({baseUrl:r})}async function Ke({homeServerUrl:r,accessToken:e,userId:t,deviceId:i}){if(console.log("createMatrixClient::",{homeServerUrl:r,accessToken:e,userId:t,deviceId:i}),!r||!e||!t||!i)throw new Error("Login to Matrix account before trying to instantiate Matrix client.");let n=ae({baseUrl:r,accessToken:e,userId:t,deviceId:i,timelineSupport:!0,cryptoCallbacks:{getSecretStorageKey:ve,cacheSecretStorageKey:Re},verificationMethods:["m.sas.v1"]});return await n.initRustCrypto({useIndexedDB:!1}),n.setMaxListeners(20),await n.startClient({lazyLoadMembers:!0,includeArchivedRooms:!1}),await new Promise((o,s)=>{let a={NULL:()=>{console.info("[NULL] state")},SYNCING:()=>{},PREPARED:()=>{console.info(`[PREPARED] state: user ${t}`),o()},RECONNECTING:()=>{console.info("[RECONNECTING] state")},CATCHUP:()=>{console.info("[CATCHUP] state")},ERROR:()=>{s(new Error("[ERROR] state: starting matrix client"))},STOPPED:()=>{console.info("[STOPPED] state")}};n.on(At.Sync,l=>{a[l]()})}),n}async function _e({mxClient:r,baseUrl:e,accessToken:t,userId:i,deviceId:n}){let o=r;o||(o=ae({baseUrl:e,accessToken:t,userId:i,deviceId:n})),o&&(o.stopClient(),await o.logout().catch(console.error),o.clearStores())}function je(r){let e=r.getAccountData("m.cross_signing.master");return console.log("hasCrossSigningAccountData::masterKeyData",e),!!e}async function Fe(r,{securityPhrase:e,password:t,forceReset:i=!1,skipBootstrapSecureStorage:n=!1}){i&&ne();let o=r.getCrypto();if(!o)throw new Error("Failed to setup matrix cross signing - failed to get matrix crypto api");if(!n){let a=await o.createRecoveryKeyFromPassphrase(e);ne(),await o.bootstrapSecretStorage({createSecretStorageKey:async()=>a,setupNewSecretStorage:i})}let s=r.getUserId();return await o.bootstrapCrossSigning({authUploadDeviceSigningKeys:async function(a){await a(Lt({userId:s,password:t}))},setupNewCrossSigning:i}),await o.resetKeyBackup(),await X(300),!!r.getAccountData("m.cross_signing.master")}function le(r){if(!r)throw new Error("Address is required to generate matrix username");return"did-ixo-"+r}function $e(r){return Buffer.from(bt(r.replace(/ /g,""))).toString("base64").slice(0,24)}function Xe(r){let e=Et(new TextEncoder().encode(r.replace(/ /g,"")));return Buffer.from(e).toString("base64").slice(0,32)}function Ut(r){return r.replace(/^(https?:\/\/)/,"").replace(/\/$/,"")}function kt(r,e=""){return"did-ixo-"+r+e}function Be(r,e){return"#"+kt(r)+":"+Ut(e)}async function Mt(r){let e="https://";/^https?:\/\//.test(r)&&(e="");let t=`${e}${r}${Pt}`;try{let o=(await(await fetch(t,{method:"GET"})).json())["m.homeserver"]?.base_url;if(o===void 0)throw new Error;return o}catch{return`${e}${r}`}}function Dt(r){return(r.indexOf("@")===0?r.substring(1):r).trim()}function Lt({userId:r,password:e}){return{type:"m.login.password",password:e,identifier:{type:"m.id.user",user:r}}}var Ve="Oracles CLI";async function qe({pin:r,oracleName:e,network:t,oracleAvatarUrl:i},n){try{let o=de.mnemonic.generateMnemonic(),s=await Me(o),a=s.baseAccount.address;console.log("\u2705 Wallet created:",a),await n(a);let l=de.did.generateSecpDid(a),c=await se(l,t);if(console.log("\u2705 DID exists:",c),!c&&(console.log("\u2705 DID does not exist, creating..."),await Ue(l,t,s),console.log("\u2705 DID created, waiting 500ms..."),await X(500),console.log("\u2705 Checking if DID exists..."),!await se(l,t)))throw new Error("Failed to create DID document");console.log("\u2705 DID created:",l);let m=de.mnemonic.generateMnemonic(12),f=C[t],S=le(a),w=$e(m),x=Xe(m);if(!await Le({homeServerUrl:f,username:S}))throw new Error("Matrix account already exists");let h=await De(a,w,Ve,s,t);if(!h?.accessToken)throw new Error("Failed to register matrix account");console.log("\u2705 Matrix account created:",h.userId);let P=await Ke({homeServerUrl:f,accessToken:h.accessToken,userId:h.userId,deviceId:h.deviceId});try{await Promise.all([P.setDisplayName(e),P.setAvatarUrl(i)])}catch(O){console.error("Failed to set display name or avatar url:",O)}let K=Wt({homeServerUrl:f,accessToken:h.accessToken}),Z=je(P);if(!Z&&(Z=await Fe(P,{securityPhrase:x,password:w,forceReset:!0}),!Z))throw new Error("Failed to setup cross signing");console.log("\u2705 Matrix cross-signing setup completed");let ot=Be(a,h.baseUrl),R=(await K.room.v1beta1.queryId(ot).catch(()=>{}))?.room_id??"";if(!R){let O=await fetch(`${k[t]}/room/source`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({did:l,userMatrixId:h.userId})});if(!O.ok)throw new Error("Failed to create matrix room");if(R=(await O.json()).roomId,!R)throw new Error("Failed to create user matrix room")}let ee=await K.room.v1beta1.listJoinedMembers(R).catch(()=>{}),te=!!ee?.joined?.[h.userId];if(!te){if(!(await K.room.v1beta1.join(R)).room_id)throw new Error("Failed to join matrix room");if(ee=await K.room.v1beta1.listJoinedMembers(R),te=!!ee?.joined?.[h.userId],!te)throw new Error("Failed to join matrix room")}console.log("\u2705 Matrix room created/joined:",R);let st=ke(m,r),ye=await fetch(`${f}/_matrix/client/r0/rooms/${R}/state/ixo.room.state.secure/encrypted_mnemonic`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.accessToken}`},body:JSON.stringify({encrypted_mnemonic:st})});if(!ye.ok)throw new Error("Failed to store encrypted mnemonic in matrix room");return await ye.json(),console.log("\u2705 Encrypted Matrix mnemonic stored in room"),await _e({mxClient:P,baseUrl:f,accessToken:h.accessToken,userId:h.userId,deviceId:h.deviceId}),{address:a,did:l,mnemonic:o,matrixUserId:h.userId,matrixRoomId:R,matrixMnemonic:m,matrixPassword:w,matrixAccessToken:h.accessToken,matrixRecoveryPhrase:x,pin:r,matrixDeviceName:Ve}}catch(o){throw console.error("Simplified registration failed:",o),o}}import{createMatrixApiClient as jt,utils as Ft}from"@ixo/matrixclient-sdk";import{CID as Kt}from"multiformats";import{base64 as _t}from"multiformats/bases/base64";import*as Ge from"multiformats/hashes/sha2";async function He(r){let e=r.startsWith("m")?r:"m"+r,t=_t.decode(e),i=await Ge.sha256.digest(t);return Kt.create(1,85,i).toString()}function ze(r){let e=new TextEncoder().encode(r);return btoa(String.fromCharCode(...Array.from(e)))}var D=async({data:r,fileName:e,config:t,wallet:i})=>{let n=jt({homeServerUrl:C[t.getValue("network")??"devnet"],accessToken:i?.matrix?.accessToken??""}),o=JSON.stringify(r),s=Buffer.from(o,"utf8"),a=e+".json",c=await n.media.v1beta1.upload(a,"application/ld+json",s),m=Ft.mxc.mxcUrlToHttp(C[t.getValue("network")??"devnet"],c.content_uri);if(!m)throw new Error("Failed to upload file to Matrix");let f=JSON.stringify(r),S=ze(f),w=await He(S);return{encrypted:"false",cid:w,proof:w,serviceEndpoint:m,mxc:c.content_uri}};var B=class{constructor(e,t){this.config=t;if(!e.did||!e.pubKey||!e.address||!e.algo)throw new Error("Wallet not found");this.wallet=e,this.MsgCreateEntityParams.value.verification=[...Je.iid.createIidVerificationMethods({did:e.did,pubkey:new Uint8Array(Buffer.from(e.pubKey)),address:e.address,controller:e.did,type:e.algo==="ed25519"?"ed":"secp"})],this.MsgCreateEntityParams.value.context=[],this.MsgCreateEntityParams.value.controller=[e.did],this.MsgCreateEntityParams.value.ownerAddress=e.address,this.MsgCreateEntityParams.value.ownerDid=e.did,this.MsgCreateEntityParams.value.service.push(E.iid.v1beta1.Service.fromPartial({id:"{id}#matrix",type:"Matrix",serviceEndpoint:"devmx.ixo.earth"})),this.MsgCreateEntityParams.value.relayerNode=we[this.config.getValue("network")??"devnet"]}wallet;MsgCreateEntityParams={typeUrl:"/ixo.entity.v1beta1.MsgCreateEntity",value:E.entity.v1beta1.MsgCreateEntity.fromPartial({entityType:"oracle",context:[],entityStatus:0,verification:[],controller:[],ownerAddress:"",ownerDid:"",relayerNode:"",service:[],linkedResource:[],accordedRight:[],linkedEntity:[],linkedClaim:[],startDate:me.proto.toTimestamp(new Date),endDate:me.proto.toTimestamp(new Date(Date.now()+100*365*24*60*60*1e3))})};async createAuthZConfig({oracleAccountAddress:e,oracleName:t,entityDid:i}){let o=await D({data:{"@context":["https://schema.org",{ixo:"https://w3id.org/ixo/context/v1",oracle:{"@id":i,"@type":"@id"}}],"@type":"Service","@id":"oracle:OracleAuthorization",name:"OracleAuthorization",description:"OracleAuthorization",serviceType:"OracleClaimAuthorizationService",requiredPermissions:["/ixo.claims.v1beta1.MsgCreateClaimAuthorization"],granteeAddress:e,granterAddress:"",oracleName:t},fileName:"authz",config:this.config,wallet:this.wallet});return E.iid.v1beta1.LinkedResource.fromPartial({id:"{id}#orz",type:"oracleAuthZConfig",proof:o.proof,right:"",encrypted:"false",mediaType:"application/json",description:"Orale AuthZ Config",serviceEndpoint:o.serviceEndpoint})}async createFeesConfig({entityDid:e,price:t}){let n=await D({data:{"@context":["https://schema.org",{ixo:"https://w3id.org/ixo/context/v1",oracle:{"@id":e,"@type":"@id"}}],"@type":"Service","@id":"oracle:ServiceFeeModel",name:"Pricing",description:"Pricing",serviceType:"",offers:{"@type":"Offer",priceCurrency:"uixo",priceSpecification:{"@type":"PaymentChargeSpecification",priceCurrency:"uixo",price:t,unitCode:"MON",billingIncrement:1,billingPeriod:"P1M",priceType:"Subscription",maxPrice:t},eligibleQuantity:{"@type":"QuantitativeValue",value:1,unitCode:"MON"}}},fileName:"fees",config:this.config,wallet:this.wallet});return E.iid.v1beta1.LinkedResource.fromPartial({id:"{id}#fee",type:"pricingList",proof:n.proof,right:"",encrypted:"false",mediaType:"application/json",description:"Pricing List",serviceEndpoint:n.serviceEndpoint})}async createOracleConfigFiles({oracleName:e,entityDid:t,price:i,oracleAccountAddress:n}){let o=this.wallet.wallet?.address;if(!this.wallet.signXClient||!this.wallet.wallet||!o)throw new Error("SignX client or wallet not found");let a=(await Promise.all([this.createAuthZConfig({oracleName:e,entityDid:t,oracleAccountAddress:n}),this.createFeesConfig({entityDid:t,price:i})])).map(m=>({typeUrl:"/ixo.iid.v1beta1.MsgAddLinkedResource",value:E.iid.v1beta1.MsgAddLinkedResource.fromPartial({id:t,linkedResource:E.iid.v1beta1.LinkedResource.fromPartial({id:m.id,description:m.description,type:m.type,proof:m.proof,mediaType:m.mediaType,encrypted:m.encrypted,serviceEndpoint:m.serviceEndpoint}),signer:o})}));y.info("Sign to edit the entity and add the config files");let l=await this.wallet.signXClient.transact(a,this.wallet.wallet);return this.wallet.signXClient.displayTransactionQRCode(JSON.stringify(l)),await this.wallet.signXClient.pollNextTransaction(),await this.wallet.signXClient.awaitTransaction()}async addPage({content:e,title:t}){let n=await D({data:{title:t,blocks:[{id:"title-block",type:"heading",props:{textColor:"default",backgroundColor:"default",textAlignment:"left"},content:[{type:"text",text:t,styles:{}}]},{id:"content-block",type:"paragraph",props:{textColor:"default",backgroundColor:"default",textAlignment:"left"},content:[{type:"text",text:e,styles:{}}]}]},fileName:"page",config:this.config,wallet:this.wallet}),o={id:"{id}#pag",type:"Settings",description:"Page",mediaType:"application/json",serviceEndpoint:n.serviceEndpoint,proof:n.proof,encrypted:"false",right:""};this.MsgCreateEntityParams.value.linkedResource.push(E.iid.v1beta1.LinkedResource.fromPartial(o))}async addProfile({orgName:e,name:t,logo:i,coverImage:n,location:o,description:s}){let l=await D({data:{"@context":{ixo:"https://w3id.org/ixo/ns/protocol/","@id":"@type",type:"@type","@protected":!1},id:"ixo:entity#profile",type:"profile",orgName:e,name:t,image:n,logo:i,brand:e,location:o,description:s},fileName:"profile",config:this.config,wallet:this.wallet}),c={id:"{id}#pro",type:"Settings",description:"Profile",mediaType:"application/json",serviceEndpoint:l.serviceEndpoint,proof:l.proof,encrypted:"false",right:""};this.MsgCreateEntityParams.value.linkedResource.push(E.iid.v1beta1.LinkedResource.fromPartial(c))}async addServices(e){this.MsgCreateEntityParams.value.service.push(...e.map(t=>E.iid.v1beta1.Service.fromPartial(t)))}async setParentProtocol(e){this.MsgCreateEntityParams.value.context.push(...Je.iid.createAgentIidContext([{key:"class",val:e}]))}returnExecutableMsg(){return this.MsgCreateEntityParams}async execute(e){y.info("Adding page"),await this.addPage(e.page),y.info("Adding profile"),await this.addProfile(e.profile),y.info("Adding services"),await this.addServices(e.services),y.info("Adding parent protocol"),await this.setParentProtocol(e.parentProtocol);let t=this.returnExecutableMsg();if(!this.wallet.signXClient||!this.wallet.wallet)throw new Error("SignX client not found");y.info("Sign this transaction to create the entity");let i=await this.wallet.signXClient.transact([t],this.wallet.wallet);this.wallet.signXClient.displayTransactionQRCode(JSON.stringify(i)),await this.wallet.signXClient.pollNextTransaction();let n=await this.wallet.signXClient.awaitTransaction();y.success("Entity created -- wait to attach the required config files"),y.info("Creating Oracle Wallet and Matrix Account");let o=await Bt({message:"Enter a PIN to secure your Matrix Vault:",initialValue:"",defaultValue:"",validate(c){return v(c,"PIN is required")}});$t(o)&&(y.error("User cancelled"),process.exit(1));let s=await qe({pin:o,oracleName:e.oracleConfig.oracleName,network:this.config.getValue("network"),oracleAvatarUrl:e.profile.logo},async c=>{await this.wallet.sendTokens(c,25e4)}),a=me.common.getValueFromEvents(n,"wasm","token_id");await this.createOracleConfigFiles({oracleName:e.oracleConfig.oracleName,price:e.oracleConfig.price,oracleAccountAddress:s.address,entityDid:a}),y.success("Entity created -- config files attached");let l=Xt();return l.start("Creating Entity Matrix Room..."),l.stop("Room created -- room joined"),y.warn("Please save the following information in a secure location as it is not stored:"),y.info("ORACLE ACCOUNT DETAILS"),y.info(`Oracle DID: ${s.did}`),y.info(`Oracle Account Address: ${s.address}`),y.info(`Oracle Account Mnemonic: ${s.mnemonic}`),y.info(`Matrix User ID: ${s.matrixUserId}`),y.info(`Matrix Password: ${s.matrixPassword}`),this.config.addValue("registerUserResult",s),this.config.addValue("entityDid",a),a}};var T=class{constructor(e,t){this.wallet=e;this.config=t;this.createEntity=new B(this.wallet,this.config)}name="create-entity";description="Create an entity";createEntity;async execute(){this.config.getValue("network")||await j(this.config);let t=await p.group({oracleName:()=>p.text({message:"What is the name of the oracle?",initialValue:"My oracle",validate(s){return v(s,"Oracle name is required")}}),oraclePrice:()=>p.text({message:"What is the price of the oracle in IXO CREDITS?",initialValue:"100",validate(s){return Ce(parseInt(s),"Oracle price is required and must be a number")}}),page:()=>p.group({title:()=>p.text({message:"What is the title of the oracle entity page?",initialValue:"AI Agent Oracle",validate(s){return v(s,"Title is required")}}),content:()=>p.text({message:"What is the content of the oracle entity page?",initialValue:"### Oracle built to help u with daily tasks",validate(s){return v(s,"Content is required")}})}),profile:()=>p.group({orgName:()=>p.text({message:"What is the name of the organization?",initialValue:"IXO",validate(s){return v(s,"Organization name is required")}}),name:()=>p.text({message:"What is the name of the profile?",initialValue:"My oracle",validate(s){return v(s,"Profile name is required")}}),logo:({results:s})=>p.text({message:"What is the logo of the profile?",initialValue:`https://api.dicebear.com/8.x/bottts/svg?seed=${s?.name??"IXO"}`,defaultValue:`https://api.dicebear.com/8.x/bottts/svg?seed=${s?.name??"IXO"}`,validate(a){return a?ie(a,"Logo is required or a valid URL"):`https://api.dicebear.com/8.x/bottts/svg?seed=${s?.name??"IXO"}`}}),coverImage:({results:s})=>p.text({message:"What is the cover image of the profile?",initialValue:s.logo,defaultValue:s.logo,validate(a){return a?ie(a,"Cover image is required or a valid URL"):s.logo}}),location:()=>p.text({message:"What is the location of your domain?",initialValue:"New York, NY",validate(s){return v(s,"Location is required")}}),description:()=>p.text({message:"What is the description of the entity (profile)?",initialValue:"We are a company that helps you with daily tasks",validate(s){return v(s,"Description is required")}})}),parentProtocol:()=>p.select({message:"What is the parent protocol of the entity?",options:[{value:"did:ixo:entity:1a76366f16570483cea72b111b27fd78",label:"IXO Oracle Protocol",hint:"default protocol"}],initialValue:"did:ixo:entity:1a76366f16570483cea72b111b27fd78"})},{onCancel:()=>{p.cancel("Operation cancelled."),process.exit(0)}}),i=await this.createEntity.execute({oracleConfig:{oracleName:t.oracleName,price:parseInt(t.oraclePrice)},page:t.page,profile:{orgName:t.profile.orgName,name:t.profile.name,logo:t.profile.logo,coverImage:t.profile.coverImage,location:t.profile.location,description:t.profile.description},services:[{id:"{id}#api",serviceEndpoint:"http://localhost:4000",type:"oracleService"},{id:"{id}#ws",serviceEndpoint:"http://localhost:4000",type:"wsService"}],parentProtocol:t.parentProtocol});p.log.info("API for the oracle is: http://localhost:4000 | You can change this after you deploy the oracle");let o=`${xe[this.config.getValue("network")??"devnet"]}/oracle/${i}/overview`;return p.log.info(`Oracle created successfully: ${i}`),p.log.info(`Oracle URL: ${o}`),{success:!0,data:`Entity created successfully: ${i}`}}};var L=class{constructor(e){this.registry=e}name="help";description="Show help information and available commands";async execute(){return{success:!0,data:`
2
+ import{cancel as Re,intro as mr,isCancel as dt,log as X,outro as pr,select as mt,spinner as gr}from"@clack/prompts";import O from"process";var B=class{commands;constructor(){this.commands=new Map}register(e){this.commands.set(e.name,e)}get(e){return this.commands.get(e)}getAll(){return Array.from(this.commands.values())}getCommandOptions(){return this.getAll().map(e=>({value:e.name,label:e.name,hint:e.description}))}};import*as f from"@clack/prompts";import{select as ut}from"@clack/prompts";import{z as V}from"zod";var b=async r=>{let e=await ut({message:"Select network: (default: devnet)",options:[{value:"mainnet",label:"Mainnet"},{value:"testnet",label:"Testnet"},{value:"devnet",label:"Devnet"}],initialValue:"devnet",maxItems:1});return r.addValue("network",e),e},Ae={mainnet:"did:ixo:entity:2f22535f8b179a51d77a0e302e68d35d",testnet:"did:ixo:entity:3d079ebc0b332aad3305bb4a51c72edb",devnet:"did:ixo:entity:2f22535f8b179a51d77a0e302e68d35d"},E={devnet:"https://devmx.ixo.earth",testnet:"https://testmx.ixo.earth",mainnet:"https://mx.ixo.earth"},K={devnet:"https://rooms.bot.devmx.ixo.earth",testnet:"https://rooms.bot.testmx.ixo.earth",mainnet:"https://rooms.bot.mx.ixo.earth"};var be={devnet:"https://ixo-portal.vercel.app",testnet:"https://ixo-portal.vercel.app",mainnet:"https://ixo-portal.vercel.app"},U={mainnet:"https://impacthub.ixo.world/rpc/",testnet:"https://testnet.ixo.earth/rpc/",devnet:"https://devnet.ixo.earth/rpc/"},Pe={devnet:"https://domain-indexer.devnet.ixo.earth/index",testnet:"https://domain-indexer.testnet.ixo.earth/index",mainnet:"https://domain-indexer.ixo.earth/index"},C=(r,e="This field is required")=>{let i=V.string().min(1,e).safeParse(r);if(!i.success)return i.error.message},de=r=>{let t=V.string().regex(/^did:ixo:entity:[a-f0-9]{64}$/,"Invalid entity DID").safeParse(r);if(!t.success)return t.error.message},q=(r,e="This url is required or a valid URL")=>{let i=V.url(e).safeParse(r);if(!i.success)return i.error.message},Ie=(r,e="This number is required")=>{let i=V.number().min(1,e).safeParse(r);if(!i.success)return i.error.message};import{isCancel as zt,log as u,spinner as Jt,text as Qt}from"@clack/prompts";import{customMessages as it,ixo as x,utils as ye}from"@ixo/impactxclient-sdk";import{utils as we}from"@ixo/impactxclient-sdk";import{createMatrixApiClient as Bt}from"@ixo/matrixclient-sdk";import{sha256 as Ot}from"@cosmjs/crypto";import{encrypt as Nt}from"eciesjs";import{ClientEvent as kt,createClient as ue}from"matrix-js-sdk";import Ut from"md5";var G=new Map;function ft(r){return G.get(r)instanceof Uint8Array}function ht(r){return G.get(r)}function me(){G.clear()}async function Te({keys:r}){let e=Object.keys(r),t=e.find(ft);if(console.info("[] getSecretStorageKey",r,e,t),!t)return null;let i=ht(t);return[t,i]}function Oe(r,e,t){G.set(r,t)}import{Bip39 as De,EnglishMnemonic as Le,Secp256k1 as pe,sha256 as xt,Slip10 as Me,Slip10Curve as We,stringToPath as Ke}from"@cosmjs/crypto";import{DirectSecp256k1HdWallet as Ct}from"@cosmjs/proto-signing";import{createQueryClient as $e,createSigningClient as vt,customMessages as Rt,ixo as Et,utils as St}from"@ixo/impactxclient-sdk";import{createCipheriv as At,randomBytes as bt}from"crypto";import{createQueryClient as br,createRegistry as wt,utils as yt}from"@ixo/impactxclient-sdk";function $(r){try{return yt.proto.fromTimestamp(r).getTime()}catch{return}}var H={BasicAllowance:"/cosmos.feegrant.v1beta1.BasicAllowance",PeriodicAllowance:"/cosmos.feegrant.v1beta1.PeriodicAllowance"};var Ne=r=>{let e=wt();return(r??[]).map(t=>{let i=t.allowance,n=e.decode(i);switch(i.typeUrl){case H.BasicAllowance:return{granter:t.granter,grantee:t.grantee,type:H.BasicAllowance,expiration:n.expiration?$(n.expiration):null,limit:n.spendLimit?.length?n.spendLimit.find(o=>o.denom==="uixo")?.amount:null,msgs:[]};case H.PeriodicAllowance:return{granter:t.granter,grantee:t.grantee,type:H.PeriodicAllowance,expiration:n.basic?.expiration?$(n.basic.expiration):null,limit:n?.periodCanSpend?n?.periodCanSpend?.find(o=>o.denom==="uixo")?.amount:n?.basic?.spendLimit?.length?n?.basic?.spendLimit?.find(o=>o.denom==="uixo")?.amount:null,msgs:[]};default:return{type:i.typeUrl,granter:t.granter,grantee:t.grantee,expiration:n.expiration?$(n.expiration):n.basic?.expiration?$(n.basic.expiration):null,limit:n.spendLimit?.length?n.spendLimit.find(o=>o.denom==="uixo")?.amount:n?.periodCanSpend?n?.periodCanSpend?.find(o=>o.denom==="uixo")?.amount:n?.basic?.spendLimit?.length?n?.basic?.spendLimit?.find(o=>o.denom==="uixo")?.amount:null,msgs:n.allowedMessages}}})},ke=r=>{if(r==null)return!1;let e=typeof r=="object"?$(r):r;return e==null?!0:e<Date.now()},Ue=r=>r==null?!1:(typeof r=="object"?Number(r?.amount??0):typeof r=="string"?Number(r??0):r)<=5e-4;async function ge(r,e){if(!e)throw new Error("Network parameter is required but was undefined");console.log(`\u{1F50D} Checking IID document for DID: ${r} on network: ${e}`);let t=U[e];if(!t)throw new Error(`Invalid network: ${e}. Valid networks are: ${Object.keys(U).join(", ")}`);console.log(`\u{1F517} Using RPC URL: ${t}`);try{return!!(await(await $e(t)).ixo.iid.v1beta1.iidDocument({id:r}))?.iidDocument?.id}catch(i){if(i.message?.includes("did document not found")||i.message?.includes("(22)"))return!1;throw console.error("Error checking IID document:",i),i}}async function _e(r,e,t){try{let i=await t.getAccounts(),{address:n,pubkey:o}=i[0]??{},s=await Pt(n,e),a=s?.length?Ne(s)?.find(l=>!!l&&!ke(l.expiration)&&!Ue(l.limit))?.granter:void 0,c={typeUrl:"/ixo.iid.v1beta1.MsgCreateIidDocument",value:Et.iid.v1beta1.MsgCreateIidDocument.fromPartial({id:r,verifications:Rt.iid.createIidVerificationMethods({did:r,pubkey:o,address:n,controller:r,type:"secp"}),signer:n,controllers:[r]})};await It({offlineSigner:t,messages:[c],feegrantGranter:a,network:e})}catch(i){throw console.error(i),i}}async function Pt(r,e){try{let t=U[e];if(!t)throw new Error(`Invalid network: ${e}`);return(await(await $e(t)).cosmos.feegrant.v1beta1.allowances({grantee:r}))?.allowances??[]}catch(t){console.error("queryAddressAllowances::",t.message);return}}var It=async({offlineSigner:r,messages:e,memo:t="Signing with Mnemonic Demo",feegrantGranter:i,network:n})=>{let o=U[n];if(!o)throw new Error(`Invalid network: ${n}`);let s=await vt(o,r),a=await r.getAccounts(),{address:c}=a[0]??{},l=await s.simulate(c,e,t),h=(l>5e4?l:(e??[]).length*5e5)*1.7,I=Tt(h),v={amount:[{denom:"uixo",amount:String(Math.round(I.average))}],gas:String(Math.round(h)),granter:i},R=await s.signAndBroadcast(c,e,v,t,void 0);if(!!R.code)throw new Error(`Error when broadcasting tx ${R.transactionHash} at height ${R.height}. Code: ${R.code}; Raw log: ${R.rawLog}`)},Tt=r=>{let e={low:.02,average:.035,high:.045},t=r<.01?.01:r;return{low:t*e.low,average:t*e.average,high:t*e.high}},z=r=>new Promise(e=>setTimeout(e,r));function je(r,e){let t=bt(16),i=At("aes-256-cbc",Buffer.from(e.padEnd(32)),t),n=i.update(r);return n=Buffer.concat([n,i.final()]),t.toString("hex")+":"+n.toString("hex")}var Xe=async r=>{let e=await Ct.fromMnemonic(r,{prefix:"ixo"}),t=(await e.getAccounts())[0],i=await De.mnemonicToSeed(new Le(r)),n=Ke("m/44'/118'/0'/0/0"),s=Me.derivePath(We.Secp256k1,i,n).privkey,a=await pe.makeKeypair(s),c=pe.compressPubkey(a.pubkey);return{mnemonic:r,did:St.did.generateSecpDid(t.address),baseAccount:t,async getAccounts(){return await e.getAccounts()},async signDirect(d,h){return await e.signDirect(d,h)},async sign(d){try{let h=await De.mnemonicToSeed(new Le(r)),I=Ke("m/44'/118'/0'/0/0"),{privkey:v}=Me.derivePath(We.Secp256k1,h,I),R=new Uint8Array(Buffer.from(d,"base64")),se=xt(R);return(await pe.createSignature(se,v)).toFixedLength().slice(0,64)}catch(h){throw console.error("Error during signature creation:",h),h}}}};var Dt="/.well-known/matrix/client",fe=async({homeServerUrl:r,username:e,password:t,deviceName:i},n=!1)=>{let o=r,s=e,a=s.match(/^@(.+):(.+\..+)$/);a&&(s=a[1],o=a[2],o=n?o:await jt(o));try{let c=Ve(o),l=await c.login("m.login.password",{identifier:{type:"m.id.user",user:Xt(s)},password:t,initial_device_display_name:i});return{accessToken:l.access_token,deviceId:l.device_id,userId:l.user_id,baseUrl:n?o:l?.well_known?.["m.homeserver"]?.base_url||c.baseUrl}}catch(c){let l=c.message;throw l==="Unknown message"&&(l="Please check your credentials"),console.error("mxLogin::",l),new Error(l)}};async function Lt(r){let e=await fetch(`${K[r]}/public-key`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error("Failed to fetch public key for encryption");return await e.json()}function Mt(r){let e={timestamp:new Date().toISOString(),address:r,service:"matrix",type:"create-account"},t=Buffer.from(JSON.stringify(e)).toString("base64");return{challenge:e,challengeBase64:t}}function Wt(r,e){let t=new Uint8Array(Buffer.from(e,"hex")),i=new Uint8Array(Buffer.from(r,"utf8")),n=Nt(t,i);return Array.from(n,o=>o.toString(16).padStart(2,"0")).join("")}async function Kt(r,e,t,i,n){let o=await Lt(n),s=Wt(e,o.publicKey),a={address:r,encryptedPassword:s,publicKeyFingerprint:o.fingerprint,secpResult:{signature:t,challenge:i}},c=await fetch(`${K[n]}/user/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok){let l=await c.json();throw new Error(l.error||"Failed to create user account")}return await c.json()}async function Fe(r,e,t,i,n){try{let{challengeBase64:o}=Mt(r),s=await i.sign(o),a=Buffer.from(s).toString("base64");if(!(await Kt(r,e,a,o,n)).success)throw new Error("Failed to create matrix account via API");let l=E[n],d=he(r);return await fe({homeServerUrl:l,username:d,password:e,deviceName:t})}catch(o){throw console.error("mxRegisterWithSecp error:",o),o}}async function Be({homeServerUrl:r,username:e}){let t=Ve(r);try{return!!await t.isUsernameAvailable(e)}catch{return!1}}function Ve(r){if(!r)throw new Error("Home server URL is required to instantiate matrix client");return ue({baseUrl:r})}async function qe({homeServerUrl:r,accessToken:e,userId:t,deviceId:i}){if(console.log("createMatrixClient::",{homeServerUrl:r,accessToken:e,userId:t,deviceId:i}),!r||!e||!t||!i)throw new Error("Login to Matrix account before trying to instantiate Matrix client.");let n=ue({baseUrl:r,accessToken:e,userId:t,deviceId:i,timelineSupport:!0,cryptoCallbacks:{getSecretStorageKey:Te,cacheSecretStorageKey:Oe},verificationMethods:["m.sas.v1"]});return await n.initRustCrypto({useIndexedDB:!1}),n.setMaxListeners(20),await n.startClient({lazyLoadMembers:!0,includeArchivedRooms:!1}),await new Promise((o,s)=>{let a={NULL:()=>{console.info("[NULL] state")},SYNCING:()=>{},PREPARED:()=>{console.info(`[PREPARED] state: user ${t}`),o()},RECONNECTING:()=>{console.info("[RECONNECTING] state")},CATCHUP:()=>{console.info("[CATCHUP] state")},ERROR:()=>{s(new Error("[ERROR] state: starting matrix client"))},STOPPED:()=>{console.info("[STOPPED] state")}};n.on(kt.Sync,c=>{a[c]()})}),n}async function Ge({mxClient:r,baseUrl:e,accessToken:t,userId:i,deviceId:n}){let o=r;o||(o=ue({baseUrl:e,accessToken:t,userId:i,deviceId:n})),o&&(o.stopClient(),await o.logout().catch(console.error),o.clearStores())}function He(r){let e=r.getAccountData("m.cross_signing.master");return console.log("hasCrossSigningAccountData::masterKeyData",e),!!e}async function ze(r,{securityPhrase:e,password:t,forceReset:i=!1,skipBootstrapSecureStorage:n=!1}){i&&me();let o=r.getCrypto();if(!o)throw new Error("Failed to setup matrix cross signing - failed to get matrix crypto api");if(!n){let a=await o.createRecoveryKeyFromPassphrase(e);me(),await o.bootstrapSecretStorage({createSecretStorageKey:async()=>a,setupNewSecretStorage:i})}let s=r.getUserId();return await o.bootstrapCrossSigning({authUploadDeviceSigningKeys:async function(a){await a(Ft({userId:s,password:t}))},setupNewCrossSigning:i}),await o.resetKeyBackup(),await z(300),!!r.getAccountData("m.cross_signing.master")}function he(r){if(!r)throw new Error("Address is required to generate matrix username");return"did-ixo-"+r}function Je(r){return Buffer.from(Ut(r.replace(/ /g,""))).toString("base64").slice(0,24)}function Qe(r){let e=Ot(new TextEncoder().encode(r.replace(/ /g,"")));return Buffer.from(e).toString("base64").slice(0,32)}function $t(r){return r.replace(/^(https?:\/\/)/,"").replace(/\/$/,"")}function _t(r,e=""){return"did-ixo-"+r+e}function Ye(r,e){return"#"+_t(r)+":"+$t(e)}async function jt(r){let e="https://";/^https?:\/\//.test(r)&&(e="");let t=`${e}${r}${Dt}`;try{let o=(await(await fetch(t,{method:"GET"})).json())["m.homeserver"]?.base_url;if(o===void 0)throw new Error;return o}catch{return`${e}${r}`}}function Xt(r){return(r.indexOf("@")===0?r.substring(1):r).trim()}function Ft({userId:r,password:e}){return{type:"m.login.password",password:e,identifier:{type:"m.id.user",user:r}}}var Ze="Oracles CLI";async function J({pin:r,oracleName:e,network:t,oracleAvatarUrl:i},n){try{let o=we.mnemonic.generateMnemonic(),s=await Xe(o),a=s.baseAccount.address;console.log("\u2705 Wallet created:",a),await n(a);let c=we.did.generateSecpDid(a),l=await ge(c,t);if(console.log("\u2705 DID exists:",l),!l&&(console.log("\u2705 DID does not exist, creating..."),await _e(c,t,s),console.log("\u2705 DID created, waiting 500ms..."),await z(500),console.log("\u2705 Checking if DID exists..."),!await ge(c,t)))throw new Error("Failed to create DID document");console.log("\u2705 DID created:",c);let d=we.mnemonic.generateMnemonic(12),h=E[t],I=he(a),v=Je(d),R=Qe(d);if(!await Be({homeServerUrl:h,username:I}))throw new Error("Matrix account already exists");let w=await Fe(a,v,Ze,s,t);if(!w?.accessToken)throw new Error("Failed to register matrix account");console.log("\u2705 Matrix account created:",w.userId);let N=await qe({homeServerUrl:h,accessToken:w.accessToken,userId:w.userId,deviceId:w.deviceId});try{await Promise.all([N.setDisplayName(e),N.setAvatarUrl(i)])}catch(k){console.error("Failed to set display name or avatar url:",k)}let F=Bt({homeServerUrl:h,accessToken:w.accessToken}),ae=He(N);if(!ae&&(ae=await ze(N,{securityPhrase:R,password:v,forceReset:!0}),!ae))throw new Error("Failed to setup cross signing");console.log("\u2705 Matrix cross-signing setup completed");let pt=Ye(a,w.baseUrl),S=(await F.room.v1beta1.queryId(pt).catch(()=>{}))?.room_id??"";if(!S){let k=await fetch(`${K[t]}/room/source`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({did:c,userMatrixId:w.userId})});if(!k.ok)throw new Error("Failed to create matrix room");if(S=(await k.json()).roomId,!S)throw new Error("Failed to create user matrix room")}let ce=await F.room.v1beta1.listJoinedMembers(S).catch(()=>{}),le=!!ce?.joined?.[w.userId];if(!le){if(!(await F.room.v1beta1.join(S)).room_id)throw new Error("Failed to join matrix room");if(ce=await F.room.v1beta1.listJoinedMembers(S),le=!!ce?.joined?.[w.userId],!le)throw new Error("Failed to join matrix room")}console.log("\u2705 Matrix room created/joined:",S);let gt=je(d,r),Se=await fetch(`${h}/_matrix/client/r0/rooms/${S}/state/ixo.room.state.secure/encrypted_mnemonic`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w.accessToken}`},body:JSON.stringify({encrypted_mnemonic:gt})});if(!Se.ok)throw new Error("Failed to store encrypted mnemonic in matrix room");return await Se.json(),console.log("\u2705 Encrypted Matrix mnemonic stored in room"),await Ge({mxClient:N,baseUrl:h,accessToken:w.accessToken,userId:w.userId,deviceId:w.deviceId}),{address:a,did:c,mnemonic:o,matrixUserId:w.userId,matrixRoomId:S,matrixMnemonic:d,matrixPassword:v,matrixAccessToken:w.accessToken,matrixRecoveryPhrase:R,pin:r,matrixDeviceName:Ze}}catch(o){throw console.error("Simplified registration failed:",o),o}}import{createMatrixApiClient as Gt,utils as Ht}from"@ixo/matrixclient-sdk";import{CID as Vt}from"multiformats";import{base64 as qt}from"multiformats/bases/base64";import*as et from"multiformats/hashes/sha2";async function tt(r){let e=r.startsWith("m")?r:"m"+r,t=qt.decode(e),i=await et.sha256.digest(t);return Vt.create(1,85,i).toString()}function rt(r){let e=new TextEncoder().encode(r);return btoa(String.fromCharCode(...Array.from(e)))}var _=async({data:r,fileName:e,config:t,wallet:i})=>{let n=Gt({homeServerUrl:E[t.getValue("network")??"devnet"],accessToken:i?.matrix?.accessToken??""}),o=JSON.stringify(r),s=Buffer.from(o,"utf8"),a=e+".json",l=await n.media.v1beta1.upload(a,"application/ld+json",s),d=Ht.mxc.mxcUrlToHttp(E[t.getValue("network")??"devnet"],l.content_uri);if(!d)throw new Error("Failed to upload file to Matrix");let h=JSON.stringify(r),I=rt(h),v=await tt(I);return{encrypted:"false",cid:v,proof:v,serviceEndpoint:d,mxc:l.content_uri}};var D=class{constructor(e,t){this.config=t;if(!e.did||!e.pubKey||!e.address||!e.algo)throw new Error("Wallet not found");this.wallet=e,this.MsgCreateEntityParams.value.verification=[...it.iid.createIidVerificationMethods({did:e.did,pubkey:new Uint8Array(Buffer.from(e.pubKey)),address:e.address,controller:e.did,type:e.algo==="ed25519"?"ed":"secp"})],this.MsgCreateEntityParams.value.context=[],this.MsgCreateEntityParams.value.controller=[e.did],this.MsgCreateEntityParams.value.ownerAddress=e.address,this.MsgCreateEntityParams.value.ownerDid=e.did,this.MsgCreateEntityParams.value.service.push(x.iid.v1beta1.Service.fromPartial({id:"{id}#matrix",type:"Matrix",serviceEndpoint:"devmx.ixo.earth"})),this.MsgCreateEntityParams.value.relayerNode=Ae[this.config.getValue("network")??"devnet"]}wallet;MsgCreateEntityParams={typeUrl:"/ixo.entity.v1beta1.MsgCreateEntity",value:x.entity.v1beta1.MsgCreateEntity.fromPartial({entityType:"oracle",context:[],entityStatus:0,verification:[],controller:[],ownerAddress:"",ownerDid:"",relayerNode:"",service:[],linkedResource:[],accordedRight:[],linkedEntity:[],linkedClaim:[],startDate:ye.proto.toTimestamp(new Date),endDate:ye.proto.toTimestamp(new Date(Date.now()+100*365*24*60*60*1e3))})};addLinkedAccounts({oracleAccountAddress:e}){if(!this.wallet.signXClient||!this.wallet.wallet)throw new Error("SignX client or wallet not found");let n=[{devnet:"did:ixo:ixo17w9u5uk4qjyjgeyqfpnp92jwy58faey9vvp3ar",testnet:"did:ixo:ixo14vjrckltpngugp03tcasfgh5qakey9n3sgm6y2",mainnet:"did:ixo:ixo1d39eutxdc0e8mnp0fmzqjdy6aaf26s9hzrk33r"}[this.config.getValue("network")],`did:ixo:${e}`].map(o=>x.iid.v1beta1.LinkedEntity.fromPartial({id:o,type:"agent",relationship:"admin",service:"matrix"}));this.MsgCreateEntityParams.value.linkedEntity=n}async createAuthZConfig({oracleAccountAddress:e,oracleName:t,entityDid:i}){let o=await _({data:{"@context":["https://schema.org",{ixo:"https://w3id.org/ixo/context/v1",oracle:{"@id":i,"@type":"@id"}}],"@type":"Service","@id":"oracle:OracleAuthorization",name:"OracleAuthorization",description:"OracleAuthorization",serviceType:"OracleClaimAuthorizationService",requiredPermissions:["/ixo.claims.v1beta1.MsgCreateClaimAuthorization"],granteeAddress:e,granterAddress:"",oracleName:t},fileName:"authz",config:this.config,wallet:this.wallet});return x.iid.v1beta1.LinkedResource.fromPartial({id:"{id}#orz",type:"oracleAuthZConfig",proof:o.proof,right:"",encrypted:"false",mediaType:"application/json",description:"Orale AuthZ Config",serviceEndpoint:o.serviceEndpoint})}async createFeesConfig({entityDid:e,price:t,denom:i}){let n={"@context":["https://schema.org",{ixo:"https://w3id.org/ixo/context/v1",oracle:{"@id":e,"@type":"@id"}}],"@type":"Service","@id":"oracle:ServiceFeeModel",name:"Pricing",description:"Pricing",serviceType:"",offers:{"@type":"Offer",priceCurrency:i,priceSpecification:{"@type":"PaymentChargeSpecification",priceCurrency:i,price:t*1e3,unitCode:"MON",billingIncrement:1,billingPeriod:"P1M",priceType:"Subscription",maxPrice:t},eligibleQuantity:{"@type":"QuantitativeValue",value:1,unitCode:"MON"}}},o=await _({data:n,fileName:"fees",config:this.config,wallet:this.wallet});return x.iid.v1beta1.LinkedResource.fromPartial({id:"{id}#fee",type:"pricingList",proof:o.proof,right:"",encrypted:"false",mediaType:"application/json",description:"Pricing List",serviceEndpoint:o.serviceEndpoint})}async addControllerToEntity(e,t){let i=this.wallet.wallet?.address;if(!this.wallet.signXClient||!this.wallet.wallet||!i)throw new Error("SignX client or wallet not found");let n={typeUrl:"/ixo.iid.v1beta1.MsgAddController",value:x.iid.v1beta1.MsgAddController.fromPartial({id:e,controllerDid:t,signer:i})};u.info(`Sign to add controller ${t} to entity ${e}`);let o=await this.wallet.signXClient.transact([n],this.wallet.wallet);this.wallet.signXClient.displayTransactionQRCode(JSON.stringify(o)),await this.wallet.signXClient.pollNextTransaction(),await this.wallet.signXClient.awaitTransaction(),u.success(`Controller ${t} added to entity ${e}`)}async createOracleConfigFiles({oracleName:e,entityDid:t,price:i,oracleAccountAddress:n}){let o=this.wallet.wallet?.address;if(!this.wallet.signXClient||!this.wallet.wallet||!o)throw new Error("SignX client or wallet not found");let a=(await Promise.all([this.createAuthZConfig({oracleName:e,entityDid:t,oracleAccountAddress:n}),this.createFeesConfig({entityDid:t,price:i,denom:this.config.getValue("network")==="devnet"?"uixo":"ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B"})])).map(d=>({typeUrl:"/ixo.iid.v1beta1.MsgAddLinkedResource",value:x.iid.v1beta1.MsgAddLinkedResource.fromPartial({id:t,linkedResource:x.iid.v1beta1.LinkedResource.fromPartial({id:d.id,description:d.description,type:d.type,proof:d.proof,mediaType:d.mediaType,encrypted:d.encrypted,serviceEndpoint:d.serviceEndpoint}),signer:o})}));u.info("Sign to edit the entity and add the config files");let c=await this.wallet.signXClient.transact(a,this.wallet.wallet);return this.wallet.signXClient.displayTransactionQRCode(JSON.stringify(c)),await this.wallet.signXClient.pollNextTransaction(),await this.wallet.signXClient.awaitTransaction()}async createDomainCard({profile:e,entityDid:t}){let i=new Date().toISOString(),n={"@context":["https://www.w3.org/ns/credentials/v2","https://w3id.org/ixo/context/v1",{schema:"https://schema.org/",ixo:"https://w3id.org/ixo/vocab/v1",prov:"http://www.w3.org/ns/prov#",proj:"https://linked.data.gov.au/def/project#",xsd:"http://www.w3.org/2001/XMLSchema#",id:"@id",type:"@type","ixo:vector":{"@container":"@list","@type":"xsd:double"},"@protected":!0}],id:`${t}#dmn`,type:["VerifiableCredential","ixo:DomainCard"],issuer:{id:this.wallet.did},validFrom:i,credentialSchema:{id:"https://github.com/ixoworld/domainCards/schemas/ixo-domain-card-1.json",type:"JsonSchema"},credentialSubject:{id:t,type:["ixo:dao"],additionalType:["schema:Organization"],name:e.name,alternateName:e.orgName!==e.name?[e.orgName]:void 0,description:e.description,logo:{type:"schema:ImageObject",id:e.logo,contentUrl:e.logo},image:[{type:"schema:ImageObject",id:e.coverImage,contentUrl:e.coverImage}],address:{type:"schema:PostalAddress",addressLocality:e.location}}},o=await _({data:n,fileName:"domainCard",config:this.config,wallet:this.wallet});return x.iid.v1beta1.LinkedResource.fromPartial({id:"{id}#dmn",type:"domainCard",proof:o.proof,right:"",encrypted:"false",mediaType:"application/json",description:"Domain Card",serviceEndpoint:o.serviceEndpoint})}async addProfile({orgName:e,name:t,logo:i,coverImage:n,location:o,description:s}){let c=await _({data:{"@context":{ixo:"https://w3id.org/ixo/ns/protocol/","@id":"@type",type:"@type","@protected":!1},id:"ixo:entity#profile",type:"profile",orgName:e,name:t,image:n,logo:i,brand:e,location:o,description:s},fileName:"profile",config:this.config,wallet:this.wallet}),l={id:"{id}#pro",type:"Settings",description:"Profile",mediaType:"application/json",serviceEndpoint:c.serviceEndpoint,proof:c.proof,encrypted:"false",right:""};this.MsgCreateEntityParams.value.linkedResource.push(x.iid.v1beta1.LinkedResource.fromPartial(l))}addServices(e){this.MsgCreateEntityParams.value.service.push(...e.map(t=>x.iid.v1beta1.Service.fromPartial(t)))}setParentProtocol(e){this.MsgCreateEntityParams.value.context.push(...it.iid.createAgentIidContext([{key:"class",val:e}]))}returnExecutableMsg(){return this.MsgCreateEntityParams}async submitToDomainIndexer(e){let t=this.config.getValue("network")??"devnet",i=Pe[t];try{let n=await fetch(i,{method:"POST",headers:{accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({did:e})});if(!n.ok){let o=await n.text();u.warn(`Failed to submit to domain indexer: ${n.status} ${o}`);return}u.success("Domain card submitted to domain indexer")}catch(n){u.warn(`Error submitting to domain indexer: ${n instanceof Error?n.message:String(n)}`)}}async execute(e){u.info("Adding profile"),await this.addProfile(e.profile),u.info("Adding services"),this.addServices(e.services),u.info("Adding parent protocol"),this.setParentProtocol(e.parentProtocol);let t=this.returnExecutableMsg();if(!this.wallet.signXClient||!this.wallet.wallet)throw new Error("SignX client not found");u.info("Creating Oracle Wallet and Matrix Account");let i=await Qt({message:"Enter a PIN to secure your Matrix Vault:",initialValue:"",defaultValue:"",validate(d){return C(d,"PIN is required")}});zt(i)&&(u.error("User cancelled"),process.exit(1));let n=await J({pin:i,oracleName:e.oracleConfig.oracleName,network:this.config.getValue("network"),oracleAvatarUrl:e.profile.logo},async d=>{await this.wallet.sendTokens(d,25e4)});this.addLinkedAccounts({oracleAccountAddress:n.address}),u.info("Sign this transaction to create the entity");let o=await this.wallet.signXClient.transact([t],this.wallet.wallet);this.wallet.signXClient.displayTransactionQRCode(JSON.stringify(o)),await this.wallet.signXClient.pollNextTransaction();let s=await this.wallet.signXClient.awaitTransaction();u.success("Entity created -- wait to attach the required config files");let a=ye.common.getValueFromEvents(s,"wasm","token_id");u.info("Creating domain card");let c=await this.createDomainCard({profile:e.profile,entityDid:a});if(this.wallet.wallet?.address){let d={typeUrl:"/ixo.iid.v1beta1.MsgAddLinkedResource",value:x.iid.v1beta1.MsgAddLinkedResource.fromPartial({id:a,linkedResource:x.iid.v1beta1.LinkedResource.fromPartial({id:c.id,description:c.description,type:c.type,proof:c.proof,mediaType:c.mediaType,encrypted:c.encrypted,serviceEndpoint:c.serviceEndpoint}),signer:this.wallet.wallet.address})};u.info("Sign to add domain card to the entity");let h=await this.wallet.signXClient.transact([d],this.wallet.wallet);this.wallet.signXClient.displayTransactionQRCode(JSON.stringify(h)),await this.wallet.signXClient.pollNextTransaction(),await this.wallet.signXClient.awaitTransaction(),u.success("Domain card added to entity")}await this.createOracleConfigFiles({oracleName:e.oracleConfig.oracleName,price:e.oracleConfig.price,oracleAccountAddress:n.address,entityDid:a}),u.success("Entity created -- config files attached");let l=Jt();l.start("Creating Entity Matrix Room..."),l.stop("Room created -- room joined"),u.warn("Please save the following information in a secure location as it is not stored:"),u.info("ORACLE ACCOUNT DETAILS");for(let d in n)u.info(`${d}: ${n[d]}`);return this.config.addValue("registerUserResult",n),this.config.addValue("entityDid",a),u.info("Submitting domain card to domain indexer"),await this.submitToDomainIndexer(a),a}};var L=class{constructor(e,t){this.wallet=e;this.config=t;this.createEntity=new D(this.wallet,this.config)}name="create-entity";description="Create an entity";createEntity;async execute(){this.config.getValue("network")||await b(this.config);let t=await f.group({oracleName:()=>f.text({message:"What is the name of the oracle?",initialValue:"My oracle",validate(s){return C(s,"Oracle name is required")}}),oraclePrice:()=>f.text({message:"What is the price of the oracle in IXO CREDITS?",initialValue:"100",validate(s){return Ie(parseInt(s),"Oracle price is required and must be a number")}}),profile:()=>f.group({orgName:()=>f.text({message:"What is the name of the organization?",initialValue:"IXO",validate(s){return C(s,"Organization name is required")}}),name:()=>f.text({message:"What is the name of the profile?",initialValue:"My oracle",validate(s){return C(s,"Profile name is required")}}),logo:({results:s})=>f.text({message:"What is the logo of the profile?",initialValue:`https://api.dicebear.com/8.x/bottts/svg?seed=${s?.name??"IXO"}`,defaultValue:`https://api.dicebear.com/8.x/bottts/svg?seed=${s?.name??"IXO"}`,validate(a){return a?q(a,"Logo is required or a valid URL"):`https://api.dicebear.com/8.x/bottts/svg?seed=${s?.name??"IXO"}`}}),coverImage:({results:s})=>f.text({message:"What is the cover image of the profile?",initialValue:s.logo,defaultValue:s.logo,validate(a){return a?q(a,"Cover image is required or a valid URL"):s.logo}}),location:()=>f.text({message:"What is the location of your domain?",initialValue:"New York, NY",validate(s){return C(s,"Location is required")}}),description:()=>f.text({message:"What is the description of the entity (profile)?",initialValue:"We are a company that helps you with daily tasks",validate(s){return C(s,"Description is required")}})}),parentProtocol:()=>f.select({message:"What is the parent protocol of the entity?",options:[{value:"did:ixo:entity:1a76366f16570483cea72b111b27fd78",label:"IXO Oracle Protocol",hint:"default protocol"}],initialValue:"did:ixo:entity:1a76366f16570483cea72b111b27fd78"}),apiUrl:()=>f.text({message:"What is the API URL of the oracle?",initialValue:"http://localhost:4000",validate(s){return q(s,"API URL is required or a valid URL")}})},{onCancel:()=>{f.cancel("Operation cancelled."),process.exit(0)}}),i=await this.createEntity.execute({oracleConfig:{oracleName:t.oracleName,price:parseInt(t.oraclePrice)},profile:{orgName:t.profile.orgName,name:t.profile.name,logo:t.profile.logo,coverImage:t.profile.coverImage,location:t.profile.location,description:t.profile.description},services:[{id:"{id}#api",serviceEndpoint:t.apiUrl,type:"oracleService"},{id:"{id}#ws",serviceEndpoint:t.apiUrl,type:"wsService"}],parentProtocol:t.parentProtocol});f.log.info(`API for the oracle is: ${t.apiUrl} | You can change this after you deploy the oracle`);let o=`${be[this.config.getValue("network")??"devnet"]}/oracle/${i}/overview`;return f.log.info(`Oracle created successfully: ${i}`),f.log.info(`Oracle URL: ${o}`),{success:!0,data:`Entity created successfully: ${i}`}}};import*as A from"@clack/prompts";var Q=class{constructor(e,t){this.wallet=e;this.config=t}name="create-user";description="Create a new user";async execute(){let e=this.config.getValue("network");e||await b(this.config);let t=await A.text({message:"Enter your PIN",initialValue:"",validate(o){return C(o,"PIN is required")}});A.isCancel(t)&&(A.log.error("User cancelled"),process.exit(1));let i=await A.text({message:"Enter your oracle name",initialValue:"My oracle",validate(o){return C(o,"Oracle name is required")}});return A.isCancel(i)&&(A.log.error("User cancelled"),process.exit(1)),{success:!0,data:await J({pin:t,oracleName:i,network:e,oracleAvatarUrl:`https://api.dicebear.com/8.x/bottts/svg?seed=${i}`},async o=>{await this.wallet.sendTokens(o,15e4)})}}};var j=class{constructor(e){this.registry=e}name="help";description="Show help information and available commands";async execute(){return{success:!0,data:`
3
3
  IXO Oracles CLI - Help
4
4
 
5
5
  USAGE:
@@ -19,12 +19,12 @@ OPTIONS:
19
19
  --help, -h Show help information
20
20
 
21
21
  For more information, visit: https://github.com/ixoworld/ixo-oracles-cli
22
- `}}};import*as d from"@clack/prompts";import{existsSync as V}from"fs";import N from"path";import Ze from"simple-git";import pe from"fs";import Qe from"path";var Ye=async r=>{let e=await ce({homeServerUrl:C[r.getOrThrow("network")],username:r.getOrThrow("registerUserResult").matrixUserId,password:r.getOrThrow("registerUserResult").matrixPassword,deviceName:r.getOrThrow("registerUserResult").matrixDeviceName}),t=r.getOrThrow("network"),i=r.getOrThrow("projectPath"),n=Qe.join(i,"apps","app",".env");console.log("Creating .env file at:",n),console.log("Project path:",i);let o=Qe.dirname(n);pe.existsSync(o)||(console.log("Creating directory:",o),pe.mkdirSync(o,{recursive:!0}));let s=`
22
+ `}}};import*as m from"@clack/prompts";import{existsSync as Y}from"fs";import M from"path";import st from"simple-git";import xe from"fs";import nt from"path";var ot=async r=>{let e=await fe({homeServerUrl:E[r.getOrThrow("network")],username:r.getOrThrow("registerUserResult").matrixUserId,password:r.getOrThrow("registerUserResult").matrixPassword,deviceName:r.getOrThrow("registerUserResult").matrixDeviceName}),t=r.getOrThrow("network"),i=r.getOrThrow("projectPath"),n=nt.join(i,"apps","app",".env");console.log("Creating .env file at:",n),console.log("Project path:",i);let o=nt.dirname(n);xe.existsSync(o)||(console.log("Creating directory:",o),xe.mkdirSync(o,{recursive:!0}));let s=`
23
23
  PORT=4000
24
24
  ORACLE_NAME=${r.getValue("projectName")}
25
25
 
26
26
  # Matrix
27
- MATRIX_BASE_URL=${C[t]}
27
+ MATRIX_BASE_URL=${E[t]}
28
28
  MATRIX_ORACLE_ADMIN_ACCESS_TOKEN=${e.accessToken}
29
29
  MATRIX_ORACLE_ADMIN_PASSWORD=${r.getOrThrow("registerUserResult").matrixPassword}
30
30
  MATRIX_ORACLE_ADMIN_USER_ID=${r.getOrThrow("registerUserResult").matrixUserId}
@@ -48,21 +48,21 @@ ORACLE_DID=${r.getOrThrow("registerUserResult").did}
48
48
  ORACLE_MNEMONIC=${r.getOrThrow("registerUserResult").mnemonic}
49
49
  MATRIX_VAULT_PIN=${r.getOrThrow("registerUserResult").pin}
50
50
  ENTITY_DID=${r.getOrThrow("entityDid")}
51
- `;try{pe.writeFileSync(n,s),console.log("\u2705 .env file created successfully at:",n)}catch(a){throw console.error("\u274C Failed to create .env file:",a),a}};var q=class{constructor(e,t){this.config=e;this.wallet=t}name="init";description="Initialize Project";async getProjectInput(){let e=await d.text({message:"What is your project named?",placeholder:"my-ixo-project",validate(o){if(!o)return"Project name is required"}});d.isCancel(e)&&(d.cancel("Operation cancelled."),process.exit(0));let t=String(e),i,n;return t.includes("/")||t.includes("\\")?(i=t,n=N.basename(t)):(n=t,i=N.join(process.cwd(),n)),this.isValidProjectName(n)||(d.note("Invalid project name. Using a valid name instead.","Warning"),n=this.sanitizeProjectName(n),i=N.join(N.dirname(i),n)),{projectPath:i,projectName:n}}isValidProjectName(e){return/^[a-zA-Z][a-zA-Z0-9-_]*$/.test(e)&&e.length>0&&e.length<=50}sanitizeProjectName(e){return e.replace(/[^a-zA-Z0-9-_]/g,"-").replace(/^-+|-+$/g,"").toLowerCase().substring(0,50)}async confirmProjectCreation(e,t){if(V(e)){let o=await d.confirm({message:`Directory "${e}" already exists. Do you want to overwrite it?`,initialValue:!1});return d.isCancel(o)&&(d.cancel("Operation cancelled."),process.exit(0)),o}let n=await d.confirm({message:`Create IXO project "${t}" in "${e}"?`,initialValue:!0});return d.isCancel(n)&&(d.cancel("Operation cancelled."),process.exit(0)),n}async selectRepo(){let e=await d.select({message:"Select a template to clone",options:[{value:"git@github.com:ixoworld/ixo-oracles-boilerplate.git",label:"IXO Oracles (Default)"},{label:"Custom template",value:"custom"}]});if(d.isCancel(e)&&(d.cancel("Operation cancelled."),process.exit(0)),e==="custom"){let t=await d.text({message:"Enter the custom template URL"});return d.isCancel(t)&&(d.cancel("Operation cancelled."),process.exit(0)),t}return e}async cloneRepo(e,t,i=!1){let n=Ze(),o=d.spinner();try{if(o.start("Cloning repository..."),i&&V(t)){let{rmSync:c}=await import("fs");c(t,{recursive:!0,force:!0})}await n.clone(e,t);let s=N.join(t,".git");if(V(s)){let{rmSync:c}=await import("fs");c(s,{recursive:!0,force:!0})}await Ze(t).init(),o.stop("Repository cloned successfully"),d.log.info("Creating Oracle Entity and Matrix Account"),(await new T(this.wallet,this.config).execute()).success?d.log.info("Oracle Entity and Matrix Account created successfully"):d.log.error("Failed to create Oracle Entity and Matrix Account"),await Ye(this.config),d.log.success(`
51
+ `;try{xe.writeFileSync(n,s),console.log("\u2705 .env file created successfully at:",n)}catch(a){throw console.error("\u274C Failed to create .env file:",a),a}};var Z=class{constructor(e,t){this.config=e;this.wallet=t}name="init";description="Initialize Project";async getProjectInput(){let e=await m.text({message:"What is your project named?",placeholder:"my-ixo-project",validate(o){if(!o)return"Project name is required"}});m.isCancel(e)&&(m.cancel("Operation cancelled."),process.exit(0));let t=String(e),i,n;return t.includes("/")||t.includes("\\")?(i=t,n=M.basename(t)):(n=t,i=M.join(process.cwd(),n)),this.isValidProjectName(n)||(m.note("Invalid project name. Using a valid name instead.","Warning"),n=this.sanitizeProjectName(n),i=M.join(M.dirname(i),n)),{projectPath:i,projectName:n}}isValidProjectName(e){return/^[a-zA-Z][a-zA-Z0-9-_]*$/.test(e)&&e.length>0&&e.length<=50}sanitizeProjectName(e){return e.replace(/[^a-zA-Z0-9-_]/g,"-").replace(/^-+|-+$/g,"").toLowerCase().substring(0,50)}async confirmProjectCreation(e,t){if(Y(e)){let o=await m.confirm({message:`Directory "${e}" already exists. Do you want to overwrite it?`,initialValue:!1});return m.isCancel(o)&&(m.cancel("Operation cancelled."),process.exit(0)),o}let n=await m.confirm({message:`Create IXO project "${t}" in "${e}"?`,initialValue:!0});return m.isCancel(n)&&(m.cancel("Operation cancelled."),process.exit(0)),n}async selectRepo(){let e=await m.select({message:"Select a template to clone",options:[{value:"git@github.com:ixoworld/ixo-oracles-boilerplate.git",label:"IXO Oracles (Default)"},{label:"Custom template",value:"custom"}]});if(m.isCancel(e)&&(m.cancel("Operation cancelled."),process.exit(0)),e==="custom"){let t=await m.text({message:"Enter the custom template URL"});return m.isCancel(t)&&(m.cancel("Operation cancelled."),process.exit(0)),t}return e}async cloneRepo(e,t,i=!1){let n=st(),o=m.spinner();try{if(o.start("Cloning repository..."),i&&Y(t)){let{rmSync:l}=await import("fs");l(t,{recursive:!0,force:!0})}await n.clone(e,t);let s=M.join(t,".git");if(Y(s)){let{rmSync:l}=await import("fs");l(s,{recursive:!0,force:!0})}await st(t).init(),o.stop("Repository cloned successfully"),m.log.info("Creating Oracle Entity and Matrix Account"),(await new L(this.wallet,this.config).execute()).success?m.log.info("Oracle Entity and Matrix Account created successfully"):m.log.error("Failed to create Oracle Entity and Matrix Account"),await ot(this.config),m.log.success(`
52
52
  \u2705 IXO project created successfully!
53
53
 
54
54
  \u{1F4C1} Location: ${t}
55
55
  \u{1F680} Next steps:
56
- cd ${N.basename(t)}
56
+ cd ${M.basename(t)}
57
57
  pnpm install
58
58
  pnpm build
59
59
  cd apps/app
60
- pnpm start:dev`)}catch(s){throw o.stop("Failed to clone repository"),s}}async execute(){try{let{projectPath:e,projectName:t}=await this.getProjectInput();if(!await this.confirmProjectCreation(e,t))return{success:!1,data:"Project creation cancelled"};this.config.addValue("projectPath",e),this.config.addValue("projectName",t);let n=await this.selectRepo();this.config.addValue("repo",n);let o=V(e);return await this.cloneRepo(n,e,o),{success:!0,data:`Project "${t}" created successfully in "${e}"`}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error occurred"}}}};import{confirm as Vt}from"@clack/prompts";var G=class{constructor(e){this.wallet=e}name="logout";description="Logout command";async execute(){return await Vt({message:"Are you sure you want to logout?",initialValue:!1})?(await this.wallet.clearWallet(),{success:!0,data:"Logged out successfully"}):{success:!1,error:"Logout cancelled"}}};import{toHex as qt}from"@cosmjs/encoding";import{createRegistry as Gt}from"@ixo/impactxclient-sdk";import{SignX as et,SIGN_X_LOGIN_ERROR as Ht,SIGN_X_LOGIN_SUCCESS as zt,SIGN_X_TRANSACT_ERROR as Jt,SIGN_X_TRANSACT_SUCCESS as Qt}from"@ixo/signx-sdk";import Yt from"qrcode-terminal";var tt={devnet:"https://signx.devnet.ixo.earth",testnet:"https://signx.testnet.ixo.earth",mainnet:"https://signx.ixo.earth"},U=class{signXClient;_loginData;get loginData(){return this._loginData}static loadFromWallet(e){return new et({endpoint:tt[e.network],sitename:"IXO Oracles CLI",network:e.network})}constructor(e){this.signXClient=new et({endpoint:tt[e],sitename:"IXO Oracles CLI",network:e})}async login(){let e=await this.signXClient.login({pollingInterval:2e3,matrix:!0});return this._loginData=e,e}displayStyledQRCode(e,t){let i=typeof e=="string"?e:JSON.stringify(e);console.log(`
61
- `+" ".repeat(5)+"\u{1F510} "+t),console.log(" ".repeat(5)+"\u{1F4F1} Scan with IXO app"),console.log(" ".repeat(5)+"\u2501".repeat(30)),Yt.generate(i,{small:!0}),console.log(" ".repeat(5)+`\u23F3 Waiting...
62
- `)}displayQRCode(e){this.displayStyledQRCode(e,"Login with SignX")}async awaitLogin(){return new Promise((e,t)=>{try{this.signXClient.on(zt,async i=>{e(i.data)}),this.signXClient.on(Ht,i=>{console.log("Login error:",i),t(i)})}catch(i){console.error("Error in connecting:",i),t(i)}})}async transact(e,t,i){let n=Gt();return this.signXClient.transact({address:t.address,did:t.did,pubkey:t.pubKey,timestamp:new Date().toISOString(),transactions:[{sequence:1,txBodyHex:qt(n.encodeTxBody({messages:e,memo:i||""}))}]})}async awaitTransaction(){return new Promise((e,t)=>{try{this.signXClient.on(Qt,i=>{e(i.data)}),this.signXClient.on(Jt,i=>{t(i)})}catch(i){console.error("Error in connecting:",i),t(i)}})}async pollNextTransaction(){return this.signXClient.pollNextTransaction()}displayTransactionQRCode(e){this.displayStyledQRCode(e,"SIGNX TRANSACTION")}};var H=class{constructor(e,t){this.wallet=e;this.config=t}name="signx-login";description="Login with SignX wallet";async execute(){try{let e=await j(this.config),t=new U(e),i=await t.login();t.displayQRCode(i);let n=await t.awaitLogin();return this.wallet.setWallet(n),this.wallet.setSignXClient(t),{success:!0,data:{message:"Successfully logged in with SignX!",wallet:{address:n.address,did:n.did,name:n.name}}}}catch(e){return{success:!1,error:e instanceof Error?`SignX login failed: ${e.message}`:"Unknown error"}}}};var ge=class extends Error{constructor(t,i="CLI_ERROR",n){super(t);this.code=i;this.suggestions=n;this.name="CLIError"}};function z(r){r instanceof ge&&(console.error(`
60
+ pnpm start:dev`)}catch(s){throw o.stop("Failed to clone repository"),s}}async execute(){try{let{projectPath:e,projectName:t}=await this.getProjectInput();if(!await this.confirmProjectCreation(e,t))return{success:!1,data:"Project creation cancelled"};this.config.addValue("projectPath",e),this.config.addValue("projectName",t);let n=await this.selectRepo();this.config.addValue("repo",n);let o=Y(e);return await this.cloneRepo(n,e,o),{success:!0,data:`Project "${t}" created successfully in "${e}"`}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error occurred"}}}};import{confirm as Yt}from"@clack/prompts";var ee=class{constructor(e){this.wallet=e}name="logout";description="Logout command";async execute(){return await Yt({message:"Are you sure you want to logout?",initialValue:!1})?(await this.wallet.clearWallet(),{success:!0,data:"Logged out successfully"}):{success:!1,error:"Logout cancelled"}}};import{toHex as Zt}from"@cosmjs/encoding";import{createRegistry as er}from"@ixo/impactxclient-sdk";import{SignX as at,SIGN_X_LOGIN_ERROR as tr,SIGN_X_LOGIN_SUCCESS as rr,SIGN_X_TRANSACT_ERROR as ir,SIGN_X_TRANSACT_SUCCESS as nr}from"@ixo/signx-sdk";import or from"qrcode-terminal";var ct={devnet:"https://signx.devnet.ixo.earth",testnet:"https://signx.testnet.ixo.earth",mainnet:"https://signx.ixo.earth"},W=class{signXClient;_loginData;get loginData(){return this._loginData}static loadFromWallet(e){return new at({endpoint:ct[e.network],sitename:"IXO Oracles CLI",network:e.network})}constructor(e){this.signXClient=new at({endpoint:ct[e],sitename:"IXO Oracles CLI",network:e})}async login(){let e=await this.signXClient.login({pollingInterval:2e3,matrix:!0});return this._loginData=e,e}displayStyledQRCode(e,t){let i=typeof e=="string"?e:JSON.stringify(e);console.log(`
61
+ `+" ".repeat(5)+"\u{1F510} "+t),console.log(" ".repeat(5)+"\u{1F4F1} Scan with IXO app"),console.log(" ".repeat(5)+"\u2501".repeat(30)),or.generate(i,{small:!0}),console.log(" ".repeat(5)+`\u23F3 Waiting...
62
+ `)}displayQRCode(e){this.displayStyledQRCode(e,"Login with SignX")}async awaitLogin(){return new Promise((e,t)=>{try{this.signXClient.on(rr,i=>{if(!i.data){t(new Error("Login failed"));return}if(!i.data.matrix){t(new Error("Matrix login failed"));return}e(i.data)}),this.signXClient.on(tr,i=>{console.log("Login error:",i),t(i)})}catch(i){console.error("Error in connecting:",i),t(i)}})}async transact(e,t,i){let n=er();return this.signXClient.transact({address:t.address,did:t.did,pubkey:t.pubKey,timestamp:new Date().toISOString(),transactions:[{sequence:1,txBodyHex:Zt(n.encodeTxBody({messages:e,memo:i||""}))}]})}async awaitTransaction(){return new Promise((e,t)=>{try{this.signXClient.on(nr,i=>{e(i.data)}),this.signXClient.on(ir,i=>{t(i)})}catch(i){console.error("Error in connecting:",i),t(i)}})}async pollNextTransaction(){return this.signXClient.pollNextTransaction()}displayTransactionQRCode(e){this.displayStyledQRCode(e,"SIGNX TRANSACTION")}};var te=class{constructor(e,t){this.wallet=e;this.config=t}name="signx-login";description="Login with SignX wallet";async execute(){try{let e=await b(this.config),t=new W(e),i=await t.login();t.displayQRCode(i);let n=await t.awaitLogin();return this.wallet.setWallet(n),this.wallet.setSignXClient(t),{success:!0,data:{message:"Successfully logged in with SignX!",wallet:{address:n.address,did:n.did,name:n.name}}}}catch(e){return{success:!1,error:e instanceof Error?`SignX login failed: ${e.message}`:"Unknown error"}}}};import*as y from"@clack/prompts";var re=class{constructor(e,t){this.wallet=e;this.config=t;this.createEntity=new D(this.wallet,this.config)}name="update-entity";description="Update an entity (add controllers, etc.)";createEntity;async execute(){this.config.getValue("network")||await b(this.config);let t=await y.group({entityDid:()=>y.text({message:"What is the DID of the entity you want to update?",initialValue:this.config.getValue("entityDid")?.toString()??"",validate(i){return de(i.toString())}}),action:()=>y.select({message:"What would you like to do?",options:[{value:"add-controller",label:"Add Controller",hint:"Add a new controller DID to the entity"}],initialValue:"add-controller"}),controllerDid:async({results:i})=>{if(i.action!=="add-controller")throw new Error("Unknown action");let n=await y.text({message:"What is the DID of the controller you want to add?",validate(o){return de(o.toString())}});return y.isCancel(n)&&(y.cancel("Operation cancelled."),process.exit(0)),n}},{onCancel:()=>{y.cancel("Operation cancelled."),process.exit(0)}});try{if(t.action==="add-controller"&&typeof t.controllerDid=="string"){let i=t.controllerDid,n=t.entityDid;return y.log.info(`Adding controller ${i} to entity ${n}`),await this.createEntity.addControllerToEntity(n,i),y.log.success(`Controller ${i} successfully added to entity ${n}`),{success:!0,data:`Controller ${i} added to entity ${n}`}}return{success:!1,error:"Unknown action"}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}}};var Ce=class extends Error{constructor(t,i="CLI_ERROR",n){super(t);this.code=i;this.suggestions=n;this.name="CLIError"}};function ie(r){r instanceof Ce&&(console.error(`
63
63
  \u274C ${r.name}: ${r.message}`),r.suggestions?.length&&(console.error(`
64
64
  Suggestions:`),r.suggestions.forEach(e=>console.error(` \u2022 ${e}`))),process.exit(1)),r instanceof Error&&(console.error(`
65
65
  \u274C Unexpected Error: ${r.message}`),r.stack&&(console.error(`
66
66
  Stack trace:`),console.error(r.stack)),process.exit(1)),console.error(`
67
- \u274C Unknown error occurred`),process.exit(1)}var J=class r{config={};static instance;constructor(){}static getInstance(){return r.instance||(r.instance=new r),r.instance}addValue(e,t){this.config[e]=t}getValue(e){return this.config[e]}getOrThrow(e){let t=this.getValue(e);if(!t)throw new Error(`Value ${e} is not set`);return t}getConfig(){return this.config}deleteValue(e){delete this.config[e]}};import{cosmos as rt}from"@ixo/impactxclient-sdk";import{existsSync as ue,readFileSync as Zt,writeFileSync as er}from"fs";import{unlink as tr}from"fs/promises";import rr from"os";import ir from"path";var A=ir.join(rr.homedir(),".wallet.json"),Q=class{wallet;signXClient;constructor(){this.loadWallet()}setSignXClient(e){this.signXClient=e}loadWallet(){if(ue(A))try{let e=Zt(A,"utf8");this.wallet=JSON.parse(e),this.setSignXClient(new U(this.wallet.network??"devnet")),console.log("Wallet loaded successfully")}catch(e){console.warn("Failed to load wallet file:",e),this.wallet=void 0}else console.log("No wallet file found")}setWallet(e){try{this.wallet=e;let t=JSON.stringify(e,null,2);er(A,t,"utf8"),console.log("Wallet saved successfully to:",A)}catch(t){throw console.error("Failed to save wallet:",t),new Error("Failed to save wallet file")}}checkWalletExists(){return ue(A)&&this.wallet!==void 0}async clearWallet(){this.wallet=void 0;try{ue(A)&&(await tr(A),console.log("Wallet file deleted successfully"))}catch(e){console.error("Failed to delete wallet file:",e)}}get did(){return this.wallet?.did}get address(){return this.wallet?.address}get name(){return this.wallet?.name}get pubKey(){return this.wallet?.pubKey}get algo(){return this.wallet?.algo}get matrix(){return this.wallet?.matrix}reloadWallet(){this.loadWallet()}async sendTokens(e,t){if(!this.address||!this.signXClient||!this.wallet)throw new Error("Wallet not loaded");let i={typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:rt.bank.v1beta1.MsgSend.fromPartial({fromAddress:this.address,toAddress:e,amount:[rt.base.v1beta1.Coin.fromPartial({amount:t.toString(),denom:"uixo"})]})},n=await this.signXClient?.transact([i],this.wallet);return this.signXClient?.displayTransactionQRCode(JSON.stringify(n)),await this.signXClient?.pollNextTransaction(),await this.signXClient?.awaitTransaction()}};var he=class{registry;config;wallet;constructor(){this.registry=new _,this.config=J.getInstance(),this.wallet=new Q}registerCommands(){this.registry.register(new q(this.config,this.wallet)),this.registry.register(new T(this.wallet,this.config)),this.registry.register(new G(this.wallet)),this.registry.register(new L(this.registry))}async showHelp(){this.wallet.setWallet({address:"0x0000000000000000000000000000000000000000",algo:"secp",did:"did:ixo:entity:1a76366f16570483cea72b111b27fd78",network:"devnet",name:"My oracle",pubKey:"0x0400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",ledgered:!1,matrix:{accessToken:"",userId:"0x0000000000000000000000000000000000000000",address:"",roomId:""}}),this.registerCommands();let t=await new L(this.registry).execute();t.success&&t.data&&console.log(t.data)}async handleAuthentication(){if(!this.wallet.checkWalletExists()){let e=await nt({message:"Login with SignX",options:[{value:"login",label:"Login"},{value:"exit",label:"Exit"}]});switch(it(e)&&(fe("Operation cancelled."),b.exit(0)),String(e)){case"login":(await new H(this.wallet,this.config).execute()).success&&W.success("Login successful");break;case"exit":fe("Operation cancelled."),b.exit(0);default:throw new Error(`Unknown command: ${e}`)}}}async executeCommand(e){let t=this.registry.get(e);if(!t)throw new Error(`Unknown command: ${e}`);let i=sr();i.start(`Executing ${t.name}...`);let n=await t.execute();i.stop(`${t.name} completed`),n.success?(W.success(`${t.name} completed successfully!`),n.data&&W.info(JSON.stringify(n.data,null,2))):W.error(`${t.name} failed: ${n.error}`)}async interactiveMode(){nr("IXO CLI"),W.warn("Keep your IXO Mobile App open while running the CLI; So u do not interrupt the signX session"),await this.handleAuthentication(),this.registerCommands();let e=await nt({message:`Welcome ${this.wallet.name}, what would you like to do?`,options:[...this.registry.getCommandOptions()],initialValue:"init"});it(e)&&(fe("Operation cancelled."),b.exit(0)),await this.executeCommand(String(e))}async argumentMode(e){let t=e[0];if(!t){await this.interactiveMode();return}if(t==="--init"){await this.handleAuthentication(),this.registerCommands(),await this.executeCommand("init");return}if(t==="--help"||t==="-h"){await this.showHelp();return}await this.handleAuthentication(),this.registerCommands(),await this.executeCommand(t)}async run(e){try{let t=e.slice(2);t.length===0?await this.interactiveMode():await this.argumentMode(t)}catch(t){z(t)}or("Thanks for using IXO CLI!"),b.exit(0)}};b.on("uncaughtException",z);b.on("unhandledRejection",z);var ar=new he;ar.run(b.argv);
67
+ \u274C Unknown error occurred`,r),process.exit(1)}var ne=class r{config={};static instance;constructor(){}static getInstance(){return r.instance||(r.instance=new r),r.instance}addValue(e,t){this.config[e]=t}getValue(e){return this.config[e]}getOrThrow(e){let t=this.getValue(e);if(!t)throw new Error(`Value ${e} is not set`);return t}getConfig(){return this.config}deleteValue(e){delete this.config[e]}};import{log as P}from"@clack/prompts";import{cosmos as lt}from"@ixo/impactxclient-sdk";import{existsSync as ve,readFileSync as sr,writeFileSync as ar}from"fs";import{unlink as cr}from"fs/promises";import lr from"os";import dr from"path";var T=dr.join(lr.homedir(),".wallet.json"),oe=class{wallet;signXClient;config;constructor(e){this.config=e,this.loadWallet()}setSignXClient(e){this.signXClient=e}loadWallet(){if(ve(T))try{let e=sr(T,"utf8");this.wallet=JSON.parse(e);let t=this.wallet.matrix.userId?.split(":")[1],n={"devmx.ixo.earth":"devnet","testmx.ixo.earth":"testnet","mx.ixo.earth":"mainnet"}[t];if(!n)throw new Error("Invalid matrix domain");this.wallet.network=n,this.config.addValue("network",n),this.setSignXClient(new W(n)),P.success(`Welcome back, ${this.wallet.name}!`),P.info(`Network: ${n}`)}catch(e){P.warning(`Failed to load wallet file: ${e instanceof Error?e.message:String(e)}`),this.wallet=void 0}else P.warning("No wallet file found")}setWallet(e){try{this.wallet=e;let t=JSON.stringify(e,null,2);ar(T,t,"utf8"),P.success(`Wallet saved successfully to: ${T}`)}catch(t){throw P.error(`Failed to save wallet: ${t instanceof Error?t.message:String(t)}`),new Error("Failed to save wallet file")}}checkWalletExists(){return ve(T)&&this.wallet!==void 0}async clearWallet(){this.wallet=void 0;try{ve(T)&&(await cr(T),P.success("Wallet file deleted successfully"))}catch(e){P.error(`Failed to delete wallet file: ${e instanceof Error?e.message:String(e)}`)}}get did(){return this.wallet?.did}get address(){return this.wallet?.address}get name(){return this.wallet?.name}get pubKey(){return this.wallet?.pubKey}get algo(){return this.wallet?.algo}get matrix(){return this.wallet?.matrix}reloadWallet(){this.loadWallet()}async sendTokens(e,t){if(!this.address||!this.signXClient||!this.wallet)throw new Error("Wallet not loaded");let i={typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:lt.bank.v1beta1.MsgSend.fromPartial({fromAddress:this.address,toAddress:e,amount:[lt.base.v1beta1.Coin.fromPartial({amount:t.toString(),denom:"uixo"})]})},n=await this.signXClient?.transact([i],this.wallet);return this.signXClient?.displayTransactionQRCode(JSON.stringify(n)),await this.signXClient?.pollNextTransaction(),await this.signXClient?.awaitTransaction()}};var Ee=class{registry;config;wallet;constructor(){this.registry=new B,this.config=ne.getInstance(),this.wallet=new oe(this.config)}registerCommands(){this.registry.register(new Z(this.config,this.wallet)),this.registry.register(new L(this.wallet,this.config)),this.registry.register(new re(this.wallet,this.config)),this.registry.register(new Q(this.wallet,this.config)),this.registry.register(new ee(this.wallet)),this.registry.register(new j(this.registry))}async showHelp(){this.wallet.setWallet({address:"0x0000000000000000000000000000000000000000",algo:"secp",did:"did:ixo:entity:1a76366f16570483cea72b111b27fd78",network:"devnet",name:"My oracle",pubKey:"0x0400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",ledgered:!1,matrix:{accessToken:"",userId:"0x0000000000000000000000000000000000000000",address:"",roomId:""}}),this.registerCommands();let t=await new j(this.registry).execute();t.success&&t.data&&console.log(t.data)}async handleAuthentication(){if(!this.wallet.checkWalletExists()){let e=await mt({message:"Login with SignX",options:[{value:"login",label:"Login"},{value:"exit",label:"Exit"}]});switch(dt(e)&&(Re("Operation cancelled."),O.exit(0)),String(e)){case"login":{(await new te(this.wallet,this.config).execute()).success&&X.success("Login successful");return}case"exit":{Re("Operation cancelled."),O.exit(0);return}default:throw new Error(`Unknown command: ${e}`)}}}async executeCommand(e){let t=this.registry.get(e);if(!t)throw new Error(`Unknown command: ${e}`);let i=gr();i.start(`Executing ${t.name}...`);let n=await t.execute();i.stop(`${t.name} completed`),n.success?(X.success(`${t.name} completed successfully!`),n.data&&X.info(JSON.stringify(n.data,null,2))):X.error(`${t.name} failed: ${n.error}`)}async interactiveMode(){mr("IXO CLI"),X.warn("Keep your IXO Mobile App open while running the CLI; So u do not interrupt the signX session"),await this.handleAuthentication(),this.registerCommands();let e=await mt({message:`Welcome ${this.wallet.name}, what would you like to do?`,options:[...this.registry.getCommandOptions()],initialValue:"init"});dt(e)&&(Re("Operation cancelled."),O.exit(0)),await this.executeCommand(String(e))}async argumentMode(e){let t=e[0];if(!t){await this.interactiveMode();return}if(t==="--init"){await this.handleAuthentication(),this.registerCommands(),await this.executeCommand("init");return}if(t==="--help"||t==="-h"){await this.showHelp();return}await this.handleAuthentication(),this.registerCommands(),await this.executeCommand(t)}async run(e){try{let t=e.slice(2);t.length===0?await this.interactiveMode():await this.argumentMode(t)}catch(t){ie(t)}pr("Thanks for using IXO CLI!"),O.exit(0)}};O.on("uncaughtException",ie);O.on("unhandledRejection",ie);var ur=new Ee;ur.run(O.argv);
68
68
  //# sourceMappingURL=cli.js.map