@latticexyz/cli 2.2.17-f88e48e47ceb4a29a3862a3f3b85891490952f0e → 2.2.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands-TC2F5WA4.js +48 -0
- package/dist/commands-TC2F5WA4.js.map +1 -0
- package/dist/mud.js +1 -1
- package/package.json +14 -13
- package/dist/commands-FEAQJW6Q.js +0 -43
- package/dist/commands-FEAQJW6Q.js.map +0 -1
package/dist/mud.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import*as i from"dotenv";i.config();async function l(){let{default:r}=await import("yargs"),{default:o}=await import("chalk"),{hideBin:e}=await import("yargs/helpers"),{logError:s}=await import("./errors-R4UWN5VJ.js"),{commands:t}=await import("./commands-
|
2
|
+
import*as i from"dotenv";i.config();async function l(){let{default:r}=await import("yargs"),{default:o}=await import("chalk"),{hideBin:e}=await import("yargs/helpers"),{logError:s}=await import("./errors-R4UWN5VJ.js"),{commands:t}=await import("./commands-TC2F5WA4.js");r(e(process.argv)).scriptName("mud").command(t).strict().fail((a,n)=>{console.error(o.red(a)),a.includes("Missing required argument")&&console.log(o.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),n!=null&&(s(n),console.log("")),process.exit(1)}).alias({h:"help"}).argv}l();
|
3
3
|
//# sourceMappingURL=mud.js.map
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@latticexyz/cli",
|
3
|
-
"version": "2.2.17
|
3
|
+
"version": "2.2.17",
|
4
4
|
"description": "Command line interface for mud",
|
5
5
|
"repository": {
|
6
6
|
"type": "git",
|
@@ -49,18 +49,19 @@
|
|
49
49
|
"yargs": "^17.7.1",
|
50
50
|
"zod": "3.23.8",
|
51
51
|
"zod-validation-error": "^1.3.0",
|
52
|
-
"@latticexyz/abi-ts": "2.2.17
|
53
|
-
"@latticexyz/block-logs-stream": "2.2.17
|
54
|
-
"@latticexyz/common": "2.2.17
|
55
|
-
"@latticexyz/config": "2.2.17
|
56
|
-
"@latticexyz/gas-report": "2.2.17
|
57
|
-
"@latticexyz/protocol-parser": "2.2.17
|
58
|
-
"@latticexyz/schema-type": "2.2.17
|
59
|
-
"@latticexyz/store": "2.2.17
|
60
|
-
"@latticexyz/store-sync": "2.2.17
|
61
|
-
"@latticexyz/utils": "2.2.17
|
62
|
-
"@latticexyz/world": "2.2.17
|
63
|
-
"@latticexyz/world-module-
|
52
|
+
"@latticexyz/abi-ts": "2.2.17",
|
53
|
+
"@latticexyz/block-logs-stream": "2.2.17",
|
54
|
+
"@latticexyz/common": "2.2.17",
|
55
|
+
"@latticexyz/config": "2.2.17",
|
56
|
+
"@latticexyz/gas-report": "2.2.17",
|
57
|
+
"@latticexyz/protocol-parser": "2.2.17",
|
58
|
+
"@latticexyz/schema-type": "2.2.17",
|
59
|
+
"@latticexyz/store": "2.2.17",
|
60
|
+
"@latticexyz/store-sync": "2.2.17",
|
61
|
+
"@latticexyz/utils": "2.2.17",
|
62
|
+
"@latticexyz/world": "2.2.17",
|
63
|
+
"@latticexyz/world-module-callwithsignature": "2.2.17",
|
64
|
+
"@latticexyz/world-module-metadata": "2.2.17"
|
64
65
|
},
|
65
66
|
"devDependencies": {
|
66
67
|
"@types/debug": "^4.1.7",
|
@@ -1,43 +0,0 @@
|
|
1
|
-
import{a as te}from"./chunk-PZL6GJOK.js";import{command as Ya}from"@latticexyz/gas-report/internal";import{command as Ga}from"@latticexyz/abi-ts/internal";import{loadConfig as St,resolveConfigPath as Ct}from"@latticexyz/config/node";import{tablegen as bt}from"@latticexyz/store/codegen";import{buildSystemsManifest as ht,worldgen as wt}from"@latticexyz/world/node";import{forge as xt}from"@latticexyz/common/foundry";import{execa as vt}from"execa";async function L({rootDir:e,config:o,foundryProfile:t=process.env.FOUNDRY_PROFILE}){await Promise.all([bt({rootDir:e,config:o}),wt({rootDir:e,config:o})]),await xt(["build"],{profile:t}),await ht({rootDir:e,config:o}),await vt("mud",["abi-ts"],{stdio:"inherit"})}import Dt from"node:path";var At={command:"build",describe:"Build contracts and generate MUD artifacts (table libraries, world interface, ABI)",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"},profile:{type:"string",desc:"The foundry profile to use"}})},async handler(e){let o=await Ct(e.configPath),t=await St(o);await L({rootDir:Dt.dirname(o),config:t,foundryProfile:e.profile}),process.exit(0)}},Re=At;import{rmSync as kt}from"fs";import{homedir as Tt}from"os";import Pt from"path";import{execa as Ot}from"execa";var Mt={command:"devnode",describe:"Start a local Ethereum node for development",builder(e){return e.options({blocktime:{type:"number",default:1,decs:"Interval in which new blocks are produced"}})},async handler({blocktime:e}){console.log("Clearing devnode history");let o=Tt();kt(Pt.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let t=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${t.join(" ")}`);let r=Ot("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
|
2
|
-
gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},$e=Mt;var Bt={command:"hello <name>",describe:"Greet <name> with Hello",builder(e){return e.options({upper:{type:"boolean"}}).positional("name",{type:"string",demandOption:!0})},handler({name:e}){let o=`Gm, ${e}!`;console.log(o),process.exit(0)}},Fe=Bt;import{loadConfig as Ht,resolveConfigPath as It}from"@latticexyz/config/node";import{tablegen as Wt}from"@latticexyz/store/codegen";import jt from"node:path";var Rt={command:"tablegen",describe:"Autogenerate MUD Store table libraries based on the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"}})},async handler(e){let o=await It(e.configPath),t=await Ht(o);await Wt({rootDir:jt.dirname(o),config:t}),process.exit(0)}},Le=Rt;import he from"node:path";import{existsSync as Jo,mkdirSync as Jn,readFileSync as qo,writeFileSync as Pe}from"node:fs";import{stringToHex as cn}from"viem";import{waitForTransactionReceipt as tr}from"viem/actions";import Ve from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import Lt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{encodeDeployData as Et,size as zt}from"viem";import Ee from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import ze from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Ne from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import Ue from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import _e from"@latticexyz/world/out/InitModule.sol/InitModule.json"assert{type:"json"};import $t from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{encodeDeployData as Ft,size as q}from"viem";import{getContractAddress as Y}from"@latticexyz/common/internal";function E(e){let o=q(Ee.deployedBytecode.object),t=Ee.bytecode.object,r=Y({deployerAddress:e,bytecode:t}),n=q(ze.deployedBytecode.object),a=ze.bytecode.object,s=Y({deployerAddress:e,bytecode:a}),i=q(Ne.deployedBytecode.object),c=Ne.bytecode.object,d=Y({deployerAddress:e,bytecode:c}),p=q(Ue.deployedBytecode.object),y=Ue.bytecode.object,u=Y({deployerAddress:e,bytecode:y}),l=q(_e.deployedBytecode.object),f=Ft({bytecode:_e.bytecode.object,abi:$t,args:[r,s,d,u]}),h=Y({deployerAddress:e,bytecode:f});return{AccessManagementSystem:{bytecode:t,deployedBytecodeSize:o,debugLabel:"access management system",address:r},BalanceTransferSystem:{bytecode:a,deployedBytecodeSize:n,debugLabel:"balance transfer system",address:s},BatchCallSystem:{bytecode:c,deployedBytecodeSize:i,debugLabel:"batch call system",address:d},RegistrationSystem:{bytecode:y,deployedBytecodeSize:p,debugLabel:"core registration system",address:u},InitModule:{bytecode:f,deployedBytecodeSize:l,debugLabel:"core module",address:h}}}import{getContractAddress as Nt}from"@latticexyz/common/internal";function re(e){let o=E(e),t=zt(Ve.deployedBytecode.object),r=Et({bytecode:Ve.bytecode.object,abi:Lt,args:[o.InitModule.address]}),n=Nt({deployerAddress:e,bytecode:r});return{...o,WorldFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world factory",address:n}}}import Ke from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.json"assert{type:"json"};import Ut from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{encodeDeployData as _t,size as Vt}from"viem";import{getContractAddress as Kt}from"@latticexyz/common/internal";function ne(e){let o=E(e),t=Vt(Ke.deployedBytecode.object),r=_t({bytecode:Ke.bytecode.object,abi:Ut,args:[o.InitModule.address]}),n=Kt({deployerAddress:e,bytecode:r});return{...o,WorldProxyFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world proxy factory",address:n}}}import{ensureContractsDeployed as Je}from"@latticexyz/common/internal";async function qe(e,o,t){if(t){let n=ne(o);return await Je({client:e,deployerAddress:o,contracts:Object.values(n)}),n.WorldProxyFactory.address}let r=re(o);return await Je({client:e,deployerAddress:o,contracts:Object.values(r)}),r.WorldFactory.address}import rr from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as nr}from"@latticexyz/common";import Ye from"debug";var O=Ye("mud:cli"),Jt=Ye("mud:cli");O.log=console.debug.bind(console);Jt.log=console.error.bind(console);var g=O.extend("deploy"),qt=O.extend("deploy");g.log=console.debug.bind(console);qt.log=console.error.bind(console);import{AbiEventSignatureNotFoundError as Zt,decodeEventLog as Xt,hexToString as Ze,parseAbi as er}from"viem";import Yt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{helloStoreEvent as Gt}from"@latticexyz/store";import{helloWorldEvent as Qt}from"@latticexyz/world";var se=[Gt,Qt],D=Yt,Ge=["2.0.0","2.0.1","2.0.2"],Qe=["2.0.0","2.0.1","2.0.2"];import{isDefined as or}from"@latticexyz/common/utils";function z(e){let o=e.map(s=>{try{return{...s,...Xt({strict:!0,abi:er(se),topics:s.topics,data:s.data})}}catch(i){if(i instanceof Zt)return;throw i}}).filter(or),{address:t,deployBlock:r,worldVersion:n,storeVersion:a}=o.reduce((s,i)=>({...s,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:Ze(i.args.worldVersion).replace(/\0+$/,"")}:null,...i.eventName==="HelloStore"?{storeVersion:Ze(i.args.storeVersion).replace(/\0+$/,"")}:null}),{});if(t==null)throw new Error("could not find world address");if(r==null)throw new Error("could not find world deploy block number");if(n==null)throw new Error("could not find world version");if(a==null)throw new Error("could not find store version");return{address:t,deployBlock:r,worldVersion:n,storeVersion:a}}async function Xe(e,o,t,r){let n=await qe(e,o,r);g("deploying world");let a=await nr(e,{chain:e.chain??null,address:n,abi:rr,functionName:"deployWorld",args:[t]});g("waiting for world deploy");let s=await tr(e,{hash:a});if(s.status!=="success")throw console.error("world deploy failed",s),new Error("world deploy failed");let i=z(s.logs);return g("deployed world to",i.address,"at block",i.deployBlock),{...i,stateBlock:i.deployBlock}}import{resourceToLabel as ie,writeContract as dr}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as lr,keySchemaToHex as ro,valueSchemaToHex as no,getSchemaTypes as N,getValueSchema as so,getKeySchema as ao}from"@latticexyz/protocol-parser/internal";import{decodeAbiParameters as eo,parseAbiParameters as oo}from"viem";import{hexToResource as sr}from"@latticexyz/common";import{hexToSchema as to}from"@latticexyz/protocol-parser/internal";import ar from"@latticexyz/store/mud.config";import{getRecords as ir}from"@latticexyz/store-sync";async function ae({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up tables for",o.address);let{records:n}=await ir({table:ar.namespaces.store.tables.Tables,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),a=n.map(s=>{let{type:i,namespace:c,name:d}=sr(s.tableId),p=to(s.keySchema),y=to(s.valueSchema),u=eo(oo("string[]"),s.abiEncodedKeyNames)[0],l=eo(oo("string[]"),s.abiEncodedFieldNames)[0],f=[...y.staticFields,...y.dynamicFields],h=Object.fromEntries(p.staticFields.map((A,k)=>[u[k],{type:A,internalType:A}])),S=Object.fromEntries(f.map((A,k)=>[l[k],{type:A,internalType:A}]));return{type:i,namespace:c,name:d,tableId:s.tableId,schema:{...h,...S},key:Object.keys(h),keySchema:h,keySchemaHex:s.keySchema,valueSchema:S,valueSchemaHex:s.valueSchema}});return g("found",a.length,"tables for",o.address),a}import cr from"p-retry";import{isDefined as mr}from"@latticexyz/common/utils";async function io({client:e,worldDeploy:o,tables:t,indexerUrl:r,chainId:n}){let a=new Map(t.map(p=>{let y=N(ao(p)),u=N(so(p)),l=ro(y),f=no(u);return[p.tableId,{...p,keySchema:y,keySchemaHex:l,valueSchema:u,valueSchemaHex:f}]})),i=(await ae({client:e,worldDeploy:o,indexerUrl:r,chainId:n})).filter(({tableId:p})=>a.has(p));if(i.length){g("existing tables:",i.map(ie).join(", "));let p=i.map(y=>{let u=a.get(y.tableId);if(y.keySchemaHex!==u.keySchemaHex||y.valueSchemaHex!==u.valueSchemaHex)return[`"${ie(y)}" table:`,` Registered schema: ${JSON.stringify({schema:N(y.schema),key:y.key})}`,` Config schema: ${JSON.stringify({schema:N(u.schema),key:u.key})}`].join(`
|
3
|
-
`)}).filter(mr);if(p.length)throw new Error(["Table schemas are immutable, but found registered tables with a different schema than what you have configured.",...p,"You can either update your config with the registered schema or change the table name to register a new table."].join(`
|
4
|
-
|
5
|
-
`)+`
|
6
|
-
`)}let c=new Set(i.map(({tableId:p})=>p)),d=t.filter(p=>!c.has(p.tableId));return d.length?(g("registering tables:",d.map(ie).join(", ")),await Promise.all(d.map(p=>{let y=N(ao(p)),u=N(so(p));return cr(()=>dr(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerTable",args:[p.tableId,lr(u),ro(y),no(u),Object.keys(y),Object.keys(u)]}),{retries:3,onFailedAttempt:()=>g(`failed to register table ${ie(p)}, retrying...`)})}))):[]}import{getAddress as I}from"viem";import{writeContract as Se,resourceToLabel as G}from"@latticexyz/common";import{hexToResource as Sr,resourceToLabel as Cr}from"@latticexyz/common";import{getFunctions as Dr}from"@latticexyz/store-sync/world";import pr from"@latticexyz/store/mud.config";import{getRecords as fr}from"@latticexyz/store-sync";async function U({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up resource IDs for",o.address);let{records:n}=await fr({table:pr.namespaces.store.tables.ResourceIds,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),a=n.map(s=>s.resourceId);return g("found",a.length,"resource IDs for",o.address),a}import{decodeValueArgs as yr,encodeKey as ur,getKeySchema as gr,getSchemaTypes as lo,getValueSchema as br}from"@latticexyz/protocol-parser/internal";import{readContract as hr}from"viem/actions";async function de({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await hr(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,ur(lo(gr(t)),r)]});return yr(lo(br(t)),{staticData:n,encodedLengths:a,dynamicData:s})}import{getAddress as wr}from"viem";import xr from"@latticexyz/world/mud.config";import{getRecords as vr}from"@latticexyz/store-sync";async function le({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up resource access for",o.address);let{records:n}=await vr({table:xr.namespaces.world.tables.ResourceAccess,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),a=n.filter(s=>s.access).map(s=>({resourceId:s.resourceId,address:wr(s.caller)}));return g("found",a.length,"resource<>address access pairs"),a}import Ar from"@latticexyz/world/mud.config";async function co({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){let[n,a,s]=await Promise.all([U({client:e,worldDeploy:o,indexerUrl:t,chainId:r}),Dr({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,indexerUrl:t,chainId:r}),le({client:e,worldDeploy:o,indexerUrl:t,chainId:r})]),i=n.map(Sr).filter(c=>c.type==="system");return g("looking up systems:",i.map(Cr).join(", ")),await Promise.all(i.map(async c=>{let{system:d,publicAccess:p}=await de({client:e,worldDeploy:o,table:Ar.namespaces.world.tables.Systems,key:{systemId:c.resourceId}}),y=a.filter(u=>u.systemId===c.resourceId);return{address:d,namespace:c.namespace,name:c.name,systemId:c.resourceId,allowAll:p,allowedAddresses:s.filter(({resourceId:u})=>u===c.resourceId).map(({address:u})=>u),worldFunctions:y}}))}import Ce from"p-retry";import{ensureContractsDeployed as kr}from"@latticexyz/common/internal";async function mo({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,systems:n,indexerUrl:a,chainId:s}){let[i,c]=await Promise.all([co({client:e,worldDeploy:r,indexerUrl:a,chainId:s}),le({client:e,worldDeploy:r,indexerUrl:a,chainId:s})]),d=n.filter(m=>i.some(b=>b.systemId===m.systemId&&I(b.address)===I(m.prepareDeploy(o,t).address)));d.length&&g("existing systems:",d.map(G).join(", "));let p=d.map(m=>m.systemId),y=n.filter(m=>!p.includes(m.systemId));if(!y.length)return[];let u=y.filter(m=>i.some(b=>b.systemId===m.systemId&&I(b.address)!==I(m.prepareDeploy(o,t).address)));u.length&&g("upgrading systems:",u.map(G).join(", "));let l=y.filter(m=>!i.some(b=>b.systemId===m.systemId));l.length&&g("registering new systems:",l.map(G).join(", ")),await kr({client:e,deployerAddress:o,contracts:y.map(m=>({bytecode:m.prepareDeploy(o,t).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,debugLabel:`${G(m)} system`}))});let f=await Promise.all(y.map(m=>Ce(()=>Se(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"registerSystem",args:[m.systemId,m.prepareDeploy(o,t).address,m.allowAll]}),{retries:3,onFailedAttempt:()=>g(`failed to register system ${G(m)}, retrying...`)}))),h=n.map(m=>m.systemId),S=c.filter(({resourceId:m})=>h.includes(m)),A=[...n.flatMap(m=>m.allowedAddresses.map(b=>({resourceId:m.systemId,address:b}))),...n.flatMap(m=>m.allowedSystemIds.map(b=>({resourceId:m.systemId,address:i.find(T=>T.systemId===b)?.address??n.find(T=>T.systemId===b)?.prepareDeploy(o,t).address})).filter(b=>b.address!=null))],k=A.filter(m=>!S.some(({resourceId:b,address:T})=>b===m.resourceId&&I(T)===I(m.address))),x=S.filter(m=>!A.some(({resourceId:b,address:T})=>b===m.resourceId&&I(T)===I(m.address)));x.length&&g("revoking",x.length,"access grants"),k.length&&g("adding",k.length,"access grants");let w=await Promise.all([...x.map(m=>Ce(()=>Se(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"revokeAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:()=>g("failed to revoke access, retrying...")})),...k.map(m=>Ce(()=>Se(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"grantAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:()=>g("failed to grant access, retrying...")}))]);return[...f,...w]}import{getAddress as Tr,parseAbi as Pr}from"viem";import{getBlock as po}from"viem/actions";import{fetchBlockLogs as Or}from"@latticexyz/block-logs-stream";var fo=new Map;async function ce(e,o,t){let r=Tr(o),n=await po(e,{blockTag:"latest"}),a=fo.get(r);if(a!=null)return{...a,stateBlock:n.number};g("looking up world deploy for",r);let[s,i]=t?[{number:t},{number:t}]:[await po(e,{blockTag:"earliest"}),n],c=await Or({publicClient:e,address:r,events:Pr(se),fromBlock:s.number,toBlock:i.number,maxBlockRange:100000n});if(c.length===0)throw new Error("could not find `HelloWorld` or `HelloStore` event");return a={...z(c.flatMap(d=>d.logs)),stateBlock:n.number},fo.set(r,a),g("found world deploy for",r,"at block",a.deployBlock),a}import{hexToResource as Mr,writeContract as Br}from"@latticexyz/common";import{getFunctions as Hr}from"@latticexyz/store-sync/world";import Ir from"p-retry";async function yo({client:e,worldDeploy:o,functions:t,indexerUrl:r,chainId:n}){let a=await Hr({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,indexerUrl:r,chainId:n}),s=Object.fromEntries(a.map(d=>[d.selector,d])),i=t.filter(d=>s[d.selector]),c=t.filter(d=>!i.includes(d));if(i.length){g("functions already registered:",i.map(p=>p.signature).join(", "));let d=i.filter(p=>p.systemId!==s[p.selector]?.systemId);d.length&&console.warn("found",d.length,"functions already registered but pointing at a different system ID:",d.map(p=>p.signature).join(", "))}return c.length?(g("registering functions:",c.map(d=>d.signature).join(", ")),Promise.all(c.map(d=>{let{namespace:p}=Mr(d.systemId),y=p===""?{functionName:"registerRootFunctionSelector",args:[d.systemId,d.systemFunctionSignature,d.systemFunctionSignature]}:{functionName:"registerFunctionSelector",args:[d.systemId,d.systemFunctionSignature]};return Ir(()=>Br(e,{chain:e.chain??null,address:o.address,abi:D,...y}),{retries:3,onFailedAttempt:()=>g(`failed to register function ${d.signature}, retrying...`)})}))):[]}import{BaseError as Wr}from"viem";import{writeContract as jr}from"@latticexyz/common";import{isDefined as Rr}from"@latticexyz/common/utils";import $r from"p-retry";import{ensureContractsDeployed as Fr}from"@latticexyz/common/internal";async function me({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,modules:n}){return n.length?(await Fr({client:e,deployerAddress:o,contracts:n.map(a=>({bytecode:a.prepareDeploy(o,t).bytecode,deployedBytecodeSize:a.deployedBytecodeSize,debugLabel:`${a.name} module`}))}),g("installing modules:",n.map(a=>a.name).join(", ")),(await Promise.all(n.map(a=>$r(async()=>{try{let s=[...D,...a.abi],i=a.prepareDeploy(o,t).address,c=a.installAsRoot?{functionName:"installRootModule",args:[i,a.installData]}:{functionName:"installModule",args:[i,a.installData]};return await jr(e,{chain:e.chain??null,address:r.address,abi:s,...c})}catch(s){if(s instanceof Wr&&s.message.includes("Module_AlreadyInstalled")){g(`module ${a.name} already installed`);return}if(a.optional){g(`optional module ${a.name} install failed, skipping`),g(s);return}throw s}},{retries:3,onFailedAttempt:()=>g(`failed to install module ${a.name}, retrying...`)})))).filter(Rr)):[]}import{getAddress as uo}from"viem";import{hexToResource as go,resourceToHex as bo,writeContract as Lr}from"@latticexyz/common";import Er from"@latticexyz/world/mud.config";async function ho({client:e,worldDeploy:o,resourceIds:t,indexerUrl:r,chainId:n}){let a=Array.from(new Set(t.map(l=>go(l).namespace))),s=await U({client:e,worldDeploy:o,indexerUrl:r,chainId:n}),i=new Set(s.map(l=>go(l).namespace));i.size&&g("found",i.size,"existing namespaces:",Array.from(i).map(l=>l===""?"<root>":l).join(", "));let c=a.filter(l=>i.has(l)),p=(await Promise.all(c.map(async l=>{let{owner:f}=await de({client:e,worldDeploy:o,table:Er.namespaces.world.tables.NamespaceOwner,key:{namespaceId:bo({type:"namespace",namespace:l,name:""})}});return[l,f]}))).filter(([,l])=>uo(l)!==uo(e.account.address)).map(([l])=>l);if(p.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${p.join(", ")}`);let y=a.filter(l=>!i.has(l));return y.length>0&&g("registering namespaces:",Array.from(y).join(", ")),Promise.all(y.map(l=>Lr(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerNamespace",args:[bo({namespace:l,type:"namespace",name:""})]})))}import{resourceToHex as mn,resourceToLabel as pn}from"@latticexyz/common";import{randomBytes as fn}from"crypto";import{stringToHex as Jr,BaseError as qr,concatHex as vo}from"viem";import{hexToResource as Yr,writeContract as Gr}from"@latticexyz/common";import{identity as Qr,isDefined as Zr}from"@latticexyz/common/utils";import De from"@latticexyz/world-module-metadata/mud.config";import Xr from"@latticexyz/world-module-metadata/out/IMetadataSystem.sol/IMetadataSystem.abi.json"assert{type:"json"};import en from"@latticexyz/world-module-metadata/out/MetadataModule.sol/MetadataModule.json"assert{type:"json"};import{isHex as zr,size as Nr}from"viem";function pe(e){return Object.entries(e).flatMap(([o,t])=>Object.entries(t).flatMap(([r,n])=>n.map(a=>({path:o,name:r,start:a.start,length:a.length}))))}import{z as B}from"zod";import{Abi as Ur}from"abitype/zod";function _r(e){return zr(e,{strict:!1})}var wo=B.object({object:B.string().refine(_r),linkReferences:B.record(B.record(B.array(B.object({start:B.number(),length:B.number()})))).optional()}),Vr=B.object({bytecode:wo,deployedBytecode:wo,abi:Ur});function fe(e){let o=Vr.parse(e),t=pe(o.bytecode.linkReferences??{});return{abi:o.abi,bytecode:o.bytecode.object,placeholders:t,deployedBytecodeSize:Nr(o.deployedBytecode.object)}}import{spliceHex as Kr}from"@latticexyz/common";import{getContractAddress as xo}from"@latticexyz/common/internal";function R(e,o){return function(r,n){let a=e;if(o.length===0)return{bytecode:a,address:xo({deployerAddress:r,bytecode:a})};if(!n)throw new Error("Libraries must be provided if there are placeholders");for(let s of o){let i=n.getAddress({name:s.name,path:s.path,deployer:r});a=Kr(a,s.start,s.length,i)}return{bytecode:a,address:xo({deployerAddress:r,bytecode:a})}}}import{getKeyTuple as So}from"@latticexyz/protocol-parser/internal";import{getRecords as on}from"@latticexyz/store-sync";import{waitForTransactions as tn}from"@latticexyz/common/internal";var ye=fe(en);async function Co({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,tags:n,valueToHex:a=Qr,indexerUrl:s,chainId:i}){g("ensuring",n.length,"resource tags"),g("looking up existing resource tags");let{records:c}=await on({table:De.tables.metadata__ResourceTag,worldAddress:r.address,chainId:i,indexerUrl:s,client:e,fromBlock:r.deployBlock,toBlock:r.stateBlock});g("found",c.length,"resource tags");let d=new Map(c.map(l=>[vo(So(De.tables.metadata__ResourceTag,l)),l.value])),y=n.map(l=>({resource:l.resourceId,tag:Jr(l.tag,{size:32}),value:a(l.value)})).filter(l=>{let f=vo(So(De.tables.metadata__ResourceTag,l));return d.get(f)!==l.value});if(y.length===0)return[];let u=await me({client:e,deployerAddress:o,worldDeploy:r,libraryMap:t,modules:[{optional:!0,name:"MetadataModule",installAsRoot:!1,installData:"0x",prepareDeploy:R(ye.bytecode,ye.placeholders),deployedBytecodeSize:ye.deployedBytecodeSize,abi:ye.abi}]});return await tn({client:e,hashes:u,debugLabel:"metadata module installation"}),g("setting",y.length,"resource tags"),(await Promise.all(y.map(async l=>{let f=Yr(l.resource),h=`${f.type}:${f.namespace}:${f.name}`;g(`tagging ${h} with ${l.tag}: ${JSON.stringify(l.value)}`);try{return await Gr(e,{chain:e.chain??null,address:r.address,abi:Xr,functionName:"metadata__setResourceTag",args:[l.resource,l.tag,l.value]})}catch(S){g(`failed to set resource tag for ${h}, skipping
|
7
|
-
${S instanceof qr?S.shortMessage:S}`)}}))).filter(Zr)}import{concatHex as rn,encodeDeployData as nn,isHex as To}from"viem";import{waitForTransactionReceipt as sn}from"viem/actions";import{resourceToHex as an,sendTransaction as dn,writeContract as Do}from"@latticexyz/common";import{ensureContractsDeployed as Ao,getContractAddress as ln,waitForTransactions as ko}from"@latticexyz/common/internal";function ke(e,o){let t=o.find(r=>r.sourcePath===e.sourcePath&&r.name===e.name);if(!t)throw new Error(`Could not find referenced artifact at "${e.sourcePath}:${e.name}".`);return t}function Po(e,o){return e.bytecode.filter(t=>!To(t)).flatMap(t=>Po(ke(t,o),o))}function Ae(e,o,t){return rn(o.bytecode.map(r=>To(r)?r:ln({deployerAddress:e,bytecode:Ae(e,ke(r,t),t)})))}async function Oo({client:e,deployerAddress:o,artifacts:t,customWorld:r}){let n=E(o);await Ao({client:e,deployerAddress:o,contracts:Object.values(n)});let a=ke(r,t),s=Po(a,t);s.length&&(g(`deploying ${s.length} world dependencies`),await Ao({client:e,deployerAddress:o,contracts:s.map(u=>Ae(o,u,t)).reverse().map(u=>({bytecode:u}))})),g("deploying custom world");let i=await dn(e,{chain:e.chain??null,data:nn({abi:a.abi,args:[],bytecode:Ae(o,a,t)})});g("waiting for custom world deploy");let c=await sn(e,{hash:i});if(c.status!=="success")throw console.error("world deploy failed",c),new Error("world deploy failed");let d=z(c.logs);g("deployed custom world to",d.address,"at block",d.deployBlock);let p=await Do(e,{chain:e.chain??null,address:d.address,abi:D,functionName:"initialize",args:[n.InitModule.address]});await ko({client:e,hashes:[p],debugLabel:"world init"});let y=await Do(e,{chain:e.chain??null,address:d.address,abi:D,functionName:"transferOwnership",args:[an({type:"namespace",namespace:"",name:""}),e.account.address]});return await ko({client:e,hashes:[y],debugLabel:"world ownership transfer"}),{...d,stateBlock:d.deployBlock}}import{uniqueBy as yn}from"@latticexyz/common/utils";function Mo({path:e,name:o}){return`${e}:${o}`}function Bo(e){let o=Object.fromEntries(e.map(r=>[Mo(r),r])),t={getAddress:({path:r,name:n,deployer:a})=>{let s=o[Mo({path:r,name:n})];if(!s)throw new Error(`Could not find library for bytecode placeholder ${r}:${n}`);return s.address??={},s.address[a]??=s.prepareDeploy(a,t).address,s.address[a]}};return t}import{ensureContractsDeployed as un,ensureDeployer as gn,waitForTransactions as Te}from"@latticexyz/common/internal";async function Ho({config:e,client:o,tables:t,systems:r,libraries:n,modules:a=[],artifacts:s,salt:i,worldAddress:c,worldDeployBlock:d,deployerAddress:p,indexerUrl:y,chainId:u}){let l=p??await gn(o),f=c?await ce(o,c,d):e.deploy.customWorld?await Oo({client:o,deployerAddress:l,artifacts:s,customWorld:e.deploy.customWorld}):await Xe(o,l,i??`0x${fn(32).toString("hex")}`,e.deploy.upgradeableWorldImplementation),h={client:o,indexerUrl:y,chainId:u,worldDeploy:f};if(!Ge.includes(f.storeVersion))throw new Error(`Unsupported Store version: ${f.storeVersion}`);if(!Qe.includes(f.worldVersion))throw new Error(`Unsupported World version: ${f.worldVersion}`);let S=Bo(n);await un({...h,deployerAddress:l,contracts:[...n.map(v=>({bytecode:v.prepareDeploy(l,S).bytecode,deployedBytecodeSize:v.deployedBytecodeSize,debugLabel:`${v.path}:${v.name} library`})),...r.map(v=>({bytecode:v.prepareDeploy(l,S).bytecode,deployedBytecodeSize:v.deployedBytecodeSize,debugLabel:`${pn(v)} system`})),...a.map(v=>({bytecode:v.prepareDeploy(l,S).bytecode,deployedBytecodeSize:v.deployedBytecodeSize,debugLabel:`${v.name} module`}))]});let A=await ho({...h,resourceIds:[...t.map(({tableId:v})=>v),...r.map(({systemId:v})=>v)]});await Te({client:o,hashes:A,debugLabel:"namespace registrations"});let k=await io({...h,tables:t}),x=await mo({...h,deployerAddress:l,libraryMap:S,systems:r});await Te({client:o,hashes:[...k,...x],debugLabel:"table and system registrations"});let w=await yo({...h,functions:r.flatMap(v=>v.worldFunctions)}),m=await me({...h,deployerAddress:l,libraryMap:S,modules:a}),b=yn([...t,...r].filter(({namespace:v,namespaceLabel:P})=>P!==v).map(({namespace:v,namespaceLabel:P})=>({resourceId:mn({type:"namespace",namespace:v,name:""}),tag:"label",value:P})),v=>v.resourceId),T=t.filter(v=>v.label!==v.name).map(({tableId:v,label:P})=>({resourceId:v,tag:"label",value:P})),j=r.flatMap(({name:v,systemId:P,label:oe,metadata:C})=>[...oe!==v?[{resourceId:P,tag:"label",value:oe}]:[],{resourceId:P,tag:"abi",value:C.abi.join(`
|
8
|
-
`)},{resourceId:P,tag:"worldAbi",value:C.worldAbi.join(`
|
9
|
-
`)}]),ee=await Co({...h,deployerAddress:l,libraryMap:S,tags:[...b,...T,...j],valueToHex:cn});return await Te({client:o,hashes:[...w,...m,...ee],debugLabel:"remaining transactions"}),g("deploy complete"),f}import{createWalletClient as qn,http as Yn,isHex as Gn,stringToHex as Qn}from"viem";import{privateKeyToAccount as Zn}from"viem/accounts";import{loadConfig as Xn,resolveConfigPath as es}from"@latticexyz/config/node";import{getOutDirectory as os,getRpcUrl as ts}from"@latticexyz/common/foundry";import V from"chalk";import{MUDError as Ko}from"@latticexyz/common/errors";import jo from"path";import{loadSystemsManifest as Cn,resolveSystems as Dn}from"@latticexyz/world/node";import{isHex as Ro,toFunctionSelector as $o,toFunctionSignature as Fo}from"viem";import{readFileSync as bn}from"fs";import hn from"path";import{MUDError as ue}from"@latticexyz/common/errors";import{size as wn}from"viem";function _(e,o,t){let r,n=hn.join(t,e,o+".json");try{r=JSON.parse(bn(n,"utf8"))}catch{throw new ue(`Error reading file at ${n}`)}let a=r?.bytecode?.object;if(!a)throw new ue(`No bytecode found in ${n}`);let s=r?.deployedBytecode?.object;if(!s)throw new ue(`No deployed bytecode found in ${n}`);let i=r?.abi;if(!i)throw new ue(`No ABI found in ${n}`);let c=pe(r?.bytecode?.linkReferences??{});return{abi:i,bytecode:a,placeholders:c,deployedBytecodeSize:wn(s)}}import{groupBy as An}from"@latticexyz/common/utils";import{readFileSync as vn}from"fs";import{globSync as Sn}from"glob";import xn from"toposort";function Io(e,o,t){let r=xn(e.flatMap(n=>t(n).map(a=>[o(n),a])));return[...e].sort((n,a)=>r.indexOf(o(n))-r.indexOf(o(a)))}function Wo(e){let t=Sn(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().map(r=>JSON.parse(vn(r,"utf8"))).flatMap(r=>{if(!r.metadata)return[];let n=Object.keys(r.metadata.settings.compilationTarget)[0],a=r.metadata.settings.compilationTarget[n],s=r.bytecode.linkReferences;return Object.entries(s).flatMap(([i,c])=>Object.keys(c).map(d=>({path:i,name:d,dependentPath:n,dependentName:a})))});return Io(t,r=>`${r.path}:${r.name}`,r=>[`${r.dependentPath}:${r.dependentName}`])}import{findUp as kn}from"find-up";import{createRequire as Tn}from"node:module";async function Lo({rootDir:e,config:o,forgeOutDir:t}){let r=await kn("package.json");if(!r)throw new Error("Could not find package.json to import relative to.");let n=Tn(r),a=o.modules.flatMap(f=>f.artifactPath==null?[]:[jo.join(n.resolve(f.artifactPath),"../../")]),s=[t,...a].flatMap(f=>Wo(f).map(h=>{let S=_(jo.basename(h.path),h.name,f);return{path:h.path,name:h.name,abi:S.abi,prepareDeploy:R(S.bytecode,S.placeholders),deployedBytecodeSize:S.deployedBytecodeSize}})),c=_("System.sol","System",t).abi.filter(f=>f.type==="function").map(Fo),d=await Dn({rootDir:e,config:o}),p=await Cn({rootDir:e,config:o}),y=d.filter(f=>!f.deploy.disabled).map(f=>{let h=p.systems.find(({systemId:w})=>w===f.systemId);if(!h)throw new Error(`System "${f.label}" not found in systems manifest. Run \`mud build\` before trying again.`);let S=_(`${f.label}.sol`,f.label,t),A=f.deploy.registerWorldFunctions?S.abi.filter(w=>w.type==="function").map(Fo).filter(w=>!c.includes(w)).map(w=>{let m=f.namespace===""?w:`${f.namespace}__${w}`;return{signature:m,selector:$o(m),systemId:f.systemId,systemFunctionSignature:w,systemFunctionSelector:$o(w)}}):[],k=f.accessList.filter(w=>Ro(w)),x=f.accessList.filter(w=>!Ro(w)).map(w=>d.find(b=>b.label===w).systemId);return{...f,allowAll:f.openAccess,allowedAddresses:k,allowedSystemIds:x,prepareDeploy:R(S.bytecode,S.placeholders),deployedBytecodeSize:S.deployedBytecodeSize,worldFunctions:A,abi:S.abi,metadata:{abi:h.abi,worldAbi:h.worldAbi}}}),u=An(y,f=>f.systemId),l=Array.from(u.values()).filter(f=>f.length>1).flat();if(l.length){let f=l.map(h=>h.name);throw new Error(`Found systems with overlapping system ID: ${f.join(", ")}.
|
10
|
-
|
11
|
-
System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}return{systems:y,libraries:s}}import{getChainId as rs}from"viem/actions";import{existsSync as Pn}from"fs";import On from"path";import Mn from"chalk";import{getScriptDirectory as Bn,forge as Hn}from"@latticexyz/common/foundry";async function Eo(e,o,t,r,n,a){let s=n?.replaceAll("\\","").split(" ")??[],i=On.join(await Bn(),e+".s.sol");if(!Pn(i)){console.log(`No script at ${i}, skipping post deploy hook`);return}console.log(Mn.blue(`Executing post deploy script at ${i}`)),await Hn(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",t,"-vvv",a?"--aws":"",...s],{profile:r})}import{kmsKeyToAccount as ns}from"@latticexyz/common/kms";import No from"node:path";import{encodeField as jn}from"@latticexyz/protocol-parser/internal";import{bytesToHex as Rn}from"viem";import{createRequire as In}from"node:module";import{findUp as Wn}from"find-up";async function zo({packageJsonPath:e,artifactPath:o}){let t;try{let r=e??await Wn("package.json",{cwd:process.cwd()});if(!r)throw new Error("Could not find package.json to import relative to.");t=In(r)(o)}catch(r){throw console.error(),console.error("Could not import contract artifact at",o),console.error(),r}return fe(t)}import{resolveWithContext as $n}from"@latticexyz/world/internal";var Fn={KeysWithValueModule:"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json",KeysInTableModule:"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json",UniqueEntityModule:"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json",Unstable_CallWithSignatureModule:"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json"};async function ge(e,o){return await Promise.all(e.modules.map(async r=>{let n=r.artifactPath;if(!n)if(r.name)n=Fn[r.name]??No.join(o,`${r.name}.sol`,`${r.name}.json`),console.warn(["","\u26A0\uFE0F Your `mud.config.ts` is using a module with a `name`, but this option is deprecated.","","To resolve this, you can replace this:","",` name: ${JSON.stringify(r.name)}`,"","with this:","",` artifactPath: ${JSON.stringify(n)}`,""].join(`
|
12
|
-
`));else throw new Error("No `artifactPath` provided for module.");let a=No.basename(n,".json"),s=await zo({artifactPath:n}),i=r.args.map(c=>$n(c,{config:e})).map(c=>{let d=c.value instanceof Uint8Array?Rn(c.value):c.value;return jn(c.type,d)});if(i.length>1)throw new Error(`${a} module should only have 0-1 args, but had ${i.length} args.`);return{name:a,installAsRoot:r.root,installData:i.length===0?"0x":i[0],prepareDeploy:R(s.bytecode,s.placeholders),deployedBytecodeSize:s.deployedBytecodeSize,abi:s.abi}}))}import{findContractArtifacts as ss}from"@latticexyz/world/node";import{getAutomine as Ln,getBlock as Uo,setAutomine as En,setIntervalMining as zn}from"viem/actions";import{getAction as Q}from"viem/utils";async function Vo(e){let o=await Nn(e).catch(()=>{});if(!(!o||o.type==="automine"))return O("Enabling automine"),await _o(e,{type:"automine"}),{reset:()=>(O("Disabling automine"),_o(e,o))}}async function Nn(e){let o={mode:"anvil",...e};return await Q(o,Ln,"getAutomine")({})?{type:"automine"}:{type:"interval",blockTime:await Un(e)}}async function _o(e,o){o.type==="automine"?await Q(e,En,"setAutomine")(!0):await Q(e,zn,"setIntervalMining")({interval:o.blockTime})}async function Un(e){let o=await Q(e,Uo,"getBlock")({blockTag:"latest"}),t=await Q(e,Uo,"getBlock")({blockNumber:o.number-1n}),r=o.timestamp-t.timestamp;return Number(r)}import{redstone as _n,garnet as Vn,rhodolite as Kn}from"@latticexyz/common/chains";var be=[_n,Vn,Kn];var M={configPath:{type:"string",desc:"Path to the MUD config file"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},saveDeployment:{type:"boolean",desc:"Save the deployment info to a file",default:!0},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},deployerAddress:{type:"string",desc:"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"},alwaysRunPostDeploy:{type:"boolean",desc:"Always run PostDeploy.s.sol after each deploy (including during upgrades). By default, PostDeploy.s.sol is only run once after a new world is deployed."},forgeScriptOptions:{type:"string",description:"Options to pass to forge script PostDeploy.s.sol"},salt:{type:"string",desc:"The deployment salt to use. Defaults to a random salt."},kms:{type:"boolean",desc:"Deploy the World with an AWS KMS key instead of local private key."},indexerUrl:{type:"string",desc:"The indexer URL to use.",required:!1}};async function K(e){let o=e.salt!=null?Gn(e.salt)?e.salt:Qn(e.salt):void 0,t=e.profile??process.env.FOUNDRY_PROFILE,r=await es(e.configPath),n=await Xn(r),a=he.dirname(r);e.printConfig&&console.log(V.green(`
|
13
|
-
Resolved config:
|
14
|
-
`),JSON.stringify(n,null,2));let s=await os(t),i=e.rpc??await ts(t);console.log(V.bgBlue(V.whiteBright(`
|
15
|
-
Deploying MUD contracts${t?" with profile "+t:""} to RPC ${i}
|
16
|
-
`))),e.skipBuild||await L({rootDir:a,config:n,foundryProfile:t});let{systems:c,libraries:d}=await Lo({rootDir:a,config:n,forgeOutDir:s}),p=await ss({forgeOutDir:s}),y=await ge(n,s),u=Object.values(n.namespaces).flatMap(b=>Object.values(b.tables)).filter(b=>!b.deploy.disabled),l=await(async()=>{if(e.kms){let b=process.env.AWS_KMS_KEY_ID;if(!b)throw new Ko("Missing `AWS_KMS_KEY_ID` environment variable. This is required when using with `--kms` option.");return await ns({keyId:b})}else{let b=process.env.PRIVATE_KEY;if(!b)throw new Ko(`Missing PRIVATE_KEY environment variable.
|
17
|
-
Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
|
18
|
-
in your contracts directory to use the default anvil private key.`);return Zn(b)}})(),f=qn({transport:Yn(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:l}),h=await rs(f),S=e.indexerUrl??be.find(b=>b.id===h)?.indexerUrl,A=e.worldAddress?as({worldAddress:e.worldAddress,worldsFile:n.deploy.worldsFile,chainId:h}):void 0;console.log("Deploying from",f.account.address);let k=await Vo(f),x=Date.now(),w=await Ho({config:n,deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,worldDeployBlock:A,client:f,tables:u,systems:c,libraries:d,modules:y,artifacts:p,indexerUrl:S,chainId:h});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await Eo(n.deploy.postDeployScript,w.address,i,t,e.forgeScriptOptions,!!e.kms),await k?.reset(),console.log(V.green("Deployment completed in",(Date.now()-x)/1e3,"seconds"));let m={worldAddress:w.address,blockNumber:Number(w.deployBlock)};if(e.saveDeployment){let b=he.join(n.deploy.deploysDirectory,h.toString());Jn(b,{recursive:!0}),Pe(he.join(b,"latest.json"),JSON.stringify(m,null,2)),Pe(he.join(b,Date.now()+".json"),JSON.stringify(m,null,2));let T=[1337,31337],j=Jo(n.deploy.worldsFile)?JSON.parse(qo(n.deploy.worldsFile,"utf-8")):{};j[h]={address:m.worldAddress,blockNumber:T.includes(h)?void 0:m.blockNumber},Pe(n.deploy.worldsFile,JSON.stringify(j,null,2)),console.log(V.bgGreen(V.whiteBright(`
|
19
|
-
Deployment result (written to ${n.deploy.worldsFile} and ${b}):
|
20
|
-
`)))}return console.log(m),w}function as({chainId:e,worldAddress:o,worldsFile:t}){let r=Jo(t)?JSON.parse(qo(t,"utf-8")):{},n=r[e]?.address===o?r[e].blockNumber:void 0;return n?BigInt(n):void 0}var is={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(M)},async handler(e){try{await K(e)}catch(o){te(o),process.exit(1)}process.exit(0)}},Yo=is;import ds from"node:path";import{loadConfig as ls,resolveConfigPath as cs}from"@latticexyz/config/node";import{worldgen as ms}from"@latticexyz/world/node";var ps={command:"worldgen",describe:"Autogenerate interfaces for Systems and World based on existing contracts and the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"},clean:{type:"boolean",desc:"Clear the worldgen directory before generating new interfaces (defaults to true)",default:!0}})},async handler(e){await fs(e),process.exit(0)}};async function fs(e){let o=await cs(e.configPath),t=await ls(o),r=ds.dirname(o);await ms({rootDir:r,config:t,clean:e.clean})}var Go=ps;import Z from"chalk";import{readFileSync as hs,writeFileSync as ws}from"fs";import Me from"path";import{MUDError as J}from"@latticexyz/common/errors";var Qo={name:"@latticexyz/cli",version:"2.2.16",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},typesVersions:{"*":{index:["./dist/index.d.ts"]}},bin:{mud:"./bin/mud.js"},files:["bin","dist"],scripts:{build:"pnpm run build:js && pnpm run build:test-tables","build:js":"tsup && chmod +x ./dist/mud.js","build:test-tables":"tsx ./scripts/generate-test-tables.ts",clean:"pnpm run clean:js && pnpm run clean:test-tables","clean:js":"shx rm -rf dist","clean:test-tables":"shx rm -rf src/**/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ark/util":"0.2.2","@aws-sdk/client-kms":"^3.556.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/block-logs-stream":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/store-sync":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-module-metadata":"workspace:*",abitype:"1.0.6","asn1.js":"^5.4.1",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",execa:"^7.0.0","find-up":"^6.3.0",glob:"^10.4.2",openurl:"^1.1.1","p-queue":"^7.4.1","p-retry":"^5.1.2",path:"^0.12.7",rxjs:"7.5.5","throttle-debounce":"^5.0.0",toposort:"^2.0.2",viem:"2.21.19",yargs:"^17.7.1",zod:"3.23.8","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/openurl":"^1.0.0","@types/throttle-debounce":"^5.0.0","@types/toposort":"^2.0.6","@types/yargs":"^17.0.10","ds-test":"https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0","forge-std":"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1",vitest:"0.34.6"}};import{globSync as xs}from"glob";import{ZodError as us,z as Zo}from"zod";var gs=Zo.object({MUD_PACKAGES:Zo.string().transform(e=>JSON.parse(e))});function bs(){try{return gs.parse({MUD_PACKAGES:'{"@latticexyz/abi-ts":{"localPath":"packages/abi-ts"},"@latticexyz/block-logs-stream":{"localPath":"packages/block-logs-stream"},"@latticexyz/cli":{"localPath":"packages/cli"},"@latticexyz/common":{"localPath":"packages/common"},"@latticexyz/config":{"localPath":"packages/config"},"create-mud":{"localPath":"packages/create-mud"},"@latticexyz/dev-tools":{"localPath":"packages/dev-tools"},"@latticexyz/entrykit":{"localPath":"packages/entrykit"},"@latticexyz/explorer":{"localPath":"packages/explorer"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/paymaster":{"localPath":"packages/paymaster"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/react":{"localPath":"packages/react"},"@latticexyz/recs":{"localPath":"packages/recs"},"@latticexyz/schema-type":{"localPath":"packages/schema-type"},"solhint-config-mud":{"localPath":"packages/solhint-config-mud"},"solhint-plugin-mud":{"localPath":"packages/solhint-plugin-mud"},"@latticexyz/stash":{"localPath":"packages/stash"},"@latticexyz/store-consumer":{"localPath":"packages/store-consumer"},"@latticexyz/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"vite-plugin-mud":{"localPath":"packages/vite-plugin-mud"},"@latticexyz/world-module-erc20":{"localPath":"packages/world-module-erc20"},"@latticexyz/world-module-metadata":{"localPath":"packages/world-module-metadata"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof us){let{...o}=e.format();console.error(`
|
21
|
-
Missing or invalid environment variables:
|
22
|
-
|
23
|
-
${Object.keys(o).join(`
|
24
|
-
`)}
|
25
|
-
`),process.exit(1)}throw e}}var Oe=bs().MUD_PACKAGES;var vs={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],t=o.reduce((n,a)=>e[a]?n+1:n,0);if(t===0)throw new J(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new J(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await Ss(e));let r=xs("**/package.json").sort().filter(n=>!n.includes("node_modules"));for(let n of r)Cs(n,e)}catch(o){te(o)}finally{process.exit(0)}}};async function Ss(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(Z.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${Qo.name}`)).json()}catch{throw new J("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new J(`Could not find npm version with tag "${e.tag}"`);return console.log(Z.green(`Latest version with tag ${e.tag}: ${t}`)),t}if(e.commit){let t=e.commit.substring(0,8),r=Object.keys(o.versions).find(n=>n.includes(t));if(!r)throw new J(`Could not find npm version based on commit "${e.commit}"`);return console.log(Z.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function Cs(e,o){let{link:t}=o,{mudVersion:r}=o,n=Ds(e),a=Object.keys(Oe),s={};for(let d in n.dependencies)a.includes(d)&&(s[d]=n.dependencies[d]);let i={};for(let d in n.devDependencies)a.includes(d)&&(i[d]=n.devDependencies[d]);for(let d in n.dependencies)a.includes(d)&&(n.dependencies[d]=c(d,"dependencies"));for(let d in n.devDependencies)a.includes(d)&&(n.devDependencies[d]=c(d,"devDependencies"));return ws(e,JSON.stringify(n,null,2)+`
|
26
|
-
`),console.log(`Updating ${e}`),Xo(s,n.dependencies),Xo(i,n.devDependencies),n;function c(d,p){return t&&(r=As(e,t,d)),r||n[p][d]}}function Ds(e){try{let o=hs(e,"utf8");return JSON.parse(o)}catch{throw new J("Could not read JSON at "+e)}}function Xo(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${Z.red(e[t])} -> ${Z.green(o[t])}`)}function As(e,o,t){let r=Me.relative(Me.dirname(e),process.cwd());return"link:"+Me.join(r,o,Oe[t].localPath)}var et=vs;import{anvil as ks,forge as Ts,getRpcUrl as Ps}from"@latticexyz/common/foundry";import Os from"chalk";var Ms={...M,port:{type:"number",description:"Port to run internal node for fork testing on",default:4242},worldAddress:{type:"string",description:"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing."},forgeOptions:{type:"string",description:"Options to pass to forge test"}},Bs={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Ms)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];ks(n)}let o=e.worldAddress?await Ps(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await K({...e,saveDeployment:!1,rpc:o})).address;console.log(Os.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Ts(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},ot=Bs;import Hs from"node:path";import tt from"node:fs";import{loadConfig as Is,resolveConfigPath as Ws}from"@latticexyz/config/node";import{MUDError as rt}from"@latticexyz/common/errors";import{cast as js,getRpcUrl as Rs}from"@latticexyz/common/foundry";import $s from"@latticexyz/world/mud.config";import{createClient as Fs,http as Ls}from"viem";import{getChainId as Es,readContract as zs}from"viem/actions";import{resolveSystems as Ns}from"@latticexyz/world/node";var Us=$s.namespaces.world.tables.Systems.tableId;function _s(e,o){if(!tt.existsSync(e))throw new rt(`Missing expected worlds.json file at "${e}"`);let t=JSON.parse(tt.readFileSync(e,"utf-8"));if(!t[o])throw new rt(`Missing chain ID ${o} in "${e}"`);return t[o].address}var Vs={command:"trace",describe:"Display the trace of a transaction",builder(e){return e.options({tx:{type:"string",required:!0,description:"Transaction hash to replay"},worldAddress:{type:"string",description:"World contract address. Defaults to the value from worlds.json, based on rpc's chainId"},configPath:{type:"string",description:"Path to the MUD config file"},profile:{type:"string",description:"The foundry profile to use"},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){let o=await Ws(e.configPath),t=Hs.dirname(o),r=e.profile??process.env.FOUNDRY_PROFILE,n=e.rpc??await Rs(r),a=await Is(o),s=Fs({transport:Ls(n)}),i=await Es(s),c=e.worldAddress??_s(a.deploy.worldsFile,i),d=await Ns({rootDir:t,config:a}),p=await Promise.all(d.map(async u=>({label:u.label,address:await zs(s,{abi:D,address:c,functionName:"getField",args:[Us,[u.systemId],0]})}))),y=await js(["run","--label",`${c}:World`,...p.map(({label:u,address:l})=>["--label",`${l}:${u}`]).flat(),`${e.tx}`]);console.log(y),process.exit(0)}},nt=Vs;import{anvil as Ks,getScriptDirectory as Js,getSrcDirectory as qs}from"@latticexyz/common/foundry";import W from"chalk";import Ys from"chokidar";import{loadConfig as Gs,resolveConfigPath as Qs}from"@latticexyz/config/node";import Zs from"path";import{homedir as Xs}from"os";import{rmSync as ea}from"fs";import{BehaviorSubject as oa,debounceTime as ta,exhaustMap as ra,filter as na}from"rxjs";import{isDefined as sa}from"@latticexyz/common/utils";var aa={rpc:M.rpc,configPath:M.configPath,alwaysRunPostDeploy:M.alwaysRunPostDeploy,forgeScriptOptions:M.forgeScriptOptions,worldAddress:M.worldAddress},ia={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(aa)},async handler(e){let o=e.rpc,t=e.configPath??await Qs(e.configPath),r=await qs(),n=await Js(),a=await Gs(t);if(!e.rpc){console.log(W.gray("Cleaning devnode cache"));let d=Xs();ea(Zs.join(d,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Ks(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let s=new oa(Date.now());Ys.watch([t,r,n],{ignoreInitial:!0}).on("all",async(d,p)=>{p.includes(t)&&(console.log(W.blue("Config changed, queuing deploy\u2026")),s.next(Date.now())),(p.includes(r)||p.includes(n))&&(p.includes(a.codegen.outputDirectory)||(console.log(W.blue("Contracts changed, queuing deploy\u2026")),s.next(Date.now())))});let i=e.worldAddress;s.pipe(ta(200),ra(async d=>{i&&console.log(W.blue("Rebuilding and upgrading world\u2026"));try{let p=await K({...e,configPath:t,rpc:o,rpcBatch:!1,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,deployerAddress:void 0,worldAddress:i,salt:"0x",kms:void 0,indexerUrl:void 0});return i=p.address,d<s.value?s.next(s.value):console.log(W.gray(`
|
27
|
-
Waiting for file changes\u2026
|
28
|
-
`)),p}catch(p){console.error(W.bgRed(W.whiteBright(`
|
29
|
-
Error while attempting deploy
|
30
|
-
`))),console.error(p),console.log(W.gray(`
|
31
|
-
Waiting for file changes\u2026
|
32
|
-
`))}}),na(sa)).subscribe()}},st=ia;import{sliceHex as la,zeroHash as ca}from"viem";import{forge as da}from"@latticexyz/common/foundry";async function $(e){let o=["verify-contract",e.address,e.name,"--rpc-url",e.rpc];e.verifier&&o.push("--verifier",e.verifier),e.verifierUrl&&o.push("--verifier-url",e.verifierUrl),await da(o,{cwd:e.cwd})}import ma from"p-queue";import{MUDError as pa}from"@latticexyz/common/errors";import{getStorageAt as fa}from"viem/actions";import{execa as Be}from"execa";import{getContractAddress as at,getDeployer as ya}from"@latticexyz/common/internal";var ua="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function it({client:e,rpc:o,systems:t,modules:r,worldAddress:n,deployerAddress:a,verifier:s,verifierUrl:i}){let c=a??await ya(e);if(!c)throw new pa("No deployer address provided or found.");let d=await fa(e,{address:n,slot:ua}),p=d&&d!==ca,y=new ma({concurrency:4});if(t.map(({name:u,bytecode:l})=>y.add(()=>$({name:u,rpc:o,verifier:s,verifierUrl:i,address:at({deployerAddress:c,bytecode:l})}).catch(f=>{console.error(`Error verifying system contract ${u}:`,f)}))),s==="sourcify")if(await Be("npm",["install"],{cwd:"node_modules/@latticexyz/store"}),await Be("npm",["install"],{cwd:"node_modules/@latticexyz/world"}),await Be("npm",["install"],{cwd:"node_modules/@latticexyz/world-modules"}),Object.entries(p?ne(c):re(c)).map(([u,{bytecode:l}])=>y.add(()=>$({cwd:"node_modules/@latticexyz/world",name:u,rpc:o,verifier:s,verifierUrl:i,address:at({deployerAddress:c,bytecode:l})}).catch(f=>{console.error(`Error verifying world factory contract ${u}:`,f)}))),r.map(({name:u,prepareDeploy:l})=>{let{address:f}=l(c);return y.add(()=>$({cwd:"node_modules/@latticexyz/world-modules",name:u,rpc:o,verifier:s,verifierUrl:i,address:f}).catch(h=>{console.error(`Error verifying module contract ${u}:`,h)}))}),p){let u=la(d,-20);y.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"WorldProxy",rpc:o,verifier:s,verifierUrl:i,address:n}).catch(l=>{console.error("Error verifying WorldProxy contract:",l)})),y.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:s,verifierUrl:i,address:u}).catch(l=>{console.error("Error verifying World contract:",l)}))}else y.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:s,verifierUrl:i,address:n}).catch(u=>{console.error("Error verifying World contract:",u)}));else console.log(""),console.log(`Note: MUD is currently unable to verify store, world, and world-modules contracts with ${s}. We are planning to expand support in a future version.`),console.log("")}import{loadConfig as ga,resolveConfigPath as ba}from"@latticexyz/config/node";import{resolveSystems as ha}from"@latticexyz/world/node";import{getOutDirectory as wa,getRpcUrl as xa}from"@latticexyz/common/foundry";import{createWalletClient as va,http as Sa}from"viem";import dt from"chalk";import Ca from"node:path";var Da={deployerAddress:{type:"string",desc:"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)"},worldAddress:{type:"string",required:!0,desc:"Verify an existing World at the given address"},configPath:{type:"string",desc:"Path to the MUD config file"},profile:{type:"string",desc:"The foundry profile to use"},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},verifier:{type:"string",desc:"The verifier to use. Defaults to blockscout",default:"blockscout"},verifierUrl:{type:"string",desc:"The verification provider."}},Aa={command:"verify",describe:"Verify contracts",builder(e){return e.options(Da)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await ba(e.configPath),r=Ca.dirname(t),n=await ga(t),a=await wa(o),s=e.rpc??await xa(o);console.log(dt.bgBlue(dt.whiteBright(`
|
33
|
-
Verifying MUD contracts${o?" with profile "+o:""} to RPC ${s}
|
34
|
-
`)));let i=va({transport:Sa(s,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),d=(await ha({rootDir:r,config:n})).map(y=>{let u=_(`${y.name}.sol`,y.name,a);return{name:y.name,bytecode:u.bytecode}}),p=await ge(n,a);await it({client:i,rpc:s,systems:d,modules:p,deployerAddress:e.deployerAddress,worldAddress:e.worldAddress,verifier:e.verifier,verifierUrl:e.verifierUrl})}},lt=Aa;import{getRpcUrl as Na}from"@latticexyz/common/foundry";import{createClient as Ua,http as _a}from"viem";import ve from"chalk";import{hexToString as He,parseAbiItem as ct,stringToHex as Ie}from"viem";import{getSchemaTypes as Ia}from"@latticexyz/protocol-parser/internal";import{hexToResource as Wa,resourceToHex as ja}from"@latticexyz/common";import We from"@latticexyz/world-module-metadata/mud.config";import{decodeValueArgs as ka,getKeyTuple as Ta,getSchemaTypes as Pa,getValueSchema as Oa}from"@latticexyz/protocol-parser/internal";import{readContract as Ma}from"viem/actions";import{mapObject as Ba}from"@latticexyz/common/utils";async function we({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await Ma(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,Ta(t,r)]}),i={...r,...ka(Pa(Oa(t)),{staticData:n,encodedLengths:a,dynamicData:s})};return Ba(t.schema,(c,d)=>i[d])}import F from"node:path";import xe from"node:fs/promises";import{getFunctions as Ra}from"@latticexyz/store-sync/world";import{abiToInterface as mt,formatSolidity as pt,formatTypescript as $a}from"@latticexyz/common/codegen";var H=O.extend("pull"),Ha=O.extend("pull");H.log=console.debug.bind(console);Ha.log=console.error.bind(console);import{defineWorld as Fa}from"@latticexyz/world";import{findUp as La}from"find-up";import{isDefined as ft}from"@latticexyz/common/utils";var Ea=new Set(["store","world","metadata"]);function yt(e){return ja({type:"namespace",namespace:e,name:""})}var X=class extends Error{constructor(t){super(`Attempted to write file at "${t}", but it already exists.`);this.filename=t;this.name="WriteFileExistsError"}};async function ut({rootDir:e,client:o,worldAddress:t,replace:r,indexerUrl:n,chainId:a}){let s=r??await La(".git",{cwd:e})!=null,i=await ce(o,t),c=await U({client:o,worldDeploy:i,indexerUrl:n,chainId:a}),d=c.map(Wa).filter(x=>!Ea.has(x.namespace)),p=await ae({client:o,worldDeploy:i,indexerUrl:n,chainId:a}),y=Object.fromEntries((await Promise.all(c.map(async x=>{let{value:w}=await we({client:o,worldDeploy:i,table:We.tables.metadata__ResourceTag,key:{resource:x,tag:Ie("label",{size:32})}}),m=He(w);return[x,m===""?null:m]}))).filter(([,x])=>x!=null));y[yt("")]??="root";let u=await Ra({client:o,worldAddress:i.address,fromBlock:i.deployBlock,toBlock:i.stateBlock,indexerUrl:n,chainId:a}),l=d.filter(x=>x.type==="namespace"),f=await Promise.all(d.filter(x=>x.type==="system").map(async({namespace:x,name:w,resourceId:m})=>{let b=yt(x),T=y[m]??w.replace(/(S(y(s(t(e(m)?)?)?)?)?)?$/,"System"),[j,ee]=await Promise.all([we({client:o,worldDeploy:i,table:We.tables.metadata__ResourceTag,key:{resource:m,tag:Ie("abi",{size:32})}}).then(C=>He(C.value)).then(C=>C!==""?C.split(`
|
35
|
-
`):[]),we({client:o,worldDeploy:i,table:We.tables.metadata__ResourceTag,key:{resource:m,tag:Ie("worldAbi",{size:32})}}).then(C=>He(C.value)).then(C=>C!==""?C.split(`
|
36
|
-
`):[])]),v=u.filter(C=>C.systemId===m),P=(j.length?j:v.map(C=>`function ${C.systemFunctionSignature}`)).map(C=>{try{return ct(C)}catch{H(`Skipping invalid system signature: ${C}`)}}).filter(ft),oe=(ee.length?ee:v.map(C=>`function ${C.signature}`)).map(C=>{try{return ct(C)}catch{H(`Skipping invalid world signature: ${C}`)}}).filter(ft);return{namespaceId:b,namespaceLabel:y[b]??x,label:T,systemId:m,namespace:x,name:w,abi:P,worldAbi:oe}}));H("generating config");let h={namespaces:Object.fromEntries(l.map(({namespace:x,resourceId:w})=>{let m=y[w]??x;return[m,{...m!==x?{namespace:x}:null,tables:Object.fromEntries(p.filter(b=>b.namespace===x).map(b=>{let T=y[b.tableId]??b.name;return[T,{...T!==b.name?{name:b.name}:null,...b.type!=="table"?{type:b.type}:null,schema:Ia(b.schema),key:b.key,deploy:{disabled:!0}}]}))}]}))};H("validating config");let S=Fa(h);H("writing config"),await je(F.join(e,"mud.config.ts"),await $a(`
|
37
|
-
import { defineWorld } from "@latticexyz/world";
|
38
|
-
|
39
|
-
export default defineWorld(${JSON.stringify(h)});
|
40
|
-
`),{overwrite:s});let A=F.join(S.sourceDirectory,"remote");s&&await xe.rm(A,{recursive:!0,force:!0});for(let x of f.filter(w=>w.abi.length)){let w=`I${x.label}`,m=F.join(A,"namespaces",x.namespaceLabel,`${w}.sol`);H("writing system interface",w,"to",m);let b=mt({name:w,systemId:x.systemId,abi:x.abi});await je(F.join(e,m),await pt(b),{overwrite:s})}let k=f.flatMap(x=>x.worldAbi);if(k.length){let x="IWorldSystems",w=F.join(A,`${x}.sol`);H("writing world systems interface to",w);let m=mt({name:x,abi:k});await je(F.join(e,w),await pt(m),{overwrite:s})}return{config:S}}async function za(e){return xe.access(e).then(()=>!0,()=>!1)}async function je(e,o,t={}){if(!t.overwrite&&await za(e))throw new X(e);await xe.mkdir(F.dirname(e),{recursive:!0}),await xe.writeFile(e,o)}import Va from"node:path";import{getChainId as Ka}from"viem/actions";var Ja={worldAddress:{type:"string",required:!0,desc:"Remote world address"},profile:{type:"string",desc:"The foundry profile to use"},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},replace:{type:"boolean",desc:"Replace existing files and directories with data from remote world."},indexerUrl:{type:"string",desc:"The indexer URL to pull from.",required:!1}},qa={command:"pull",describe:"Pull mud.config.ts and interfaces from an existing world.",builder(e){return e.options(Ja)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=e.rpc??await Na(o),r=Ua({transport:_a(t,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),n=await Ka(r),a=e.indexerUrl??be.find(i=>i.id===n)?.indexerUrl;console.log(ve.bgBlue(ve.whiteBright(`
|
41
|
-
Pulling MUD config from world at ${e.worldAddress}
|
42
|
-
`)));let s=process.cwd();try{let{config:i}=await ut({rootDir:s,client:r,worldAddress:e.worldAddress,indexerUrl:a,chainId:n,replace:e.replace});await L({rootDir:s,config:i,foundryProfile:o})}catch(i){if(i instanceof X){console.log(),console.log(ve.bgRed(ve.whiteBright(" Error "))),console.log(` Attempted to write file at "${Va.relative(s,i.filename)}", but it already exists.`),console.log(),console.log(" To overwrite files, use `--replace` when running this command."),console.log();return}throw i}}},gt=qa;var Zy=[Re,Yo,$e,Ya,Fe,Le,Go,et,ot,nt,st,Ga,lt,gt];export{Zy as commands};
|
43
|
-
//# sourceMappingURL=commands-FEAQJW6Q.js.map
|