@latticexyz/cli 2.0.12 → 2.0.13-main-745420b36

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.
@@ -10,7 +10,7 @@ gracefully shutting down from SIGINT (Crtl-C)`),t.kill(),process.exit()}),await
10
10
  Bytecode for ${r} (${t} bytes) is over the contract size limit (${N} bytes). Run \`forge build --sizes\` for more info.
11
11
  `):t>N*.95&&console.warn(`
12
12
  Bytecode for ${r} (${t} bytes) is almost over the contract size limit (${N} bytes). Run \`forge build --sizes\` for more info.
13
- `),l("deploying",r,"at",s),[await jt(()=>Mt(e,{chain:e.chain??null,to:o,data:Ot([S,n])}),{retries:3,onFailedAttempt:async a=>{let c=a.attemptNumber*500;l(`failed to deploy ${r}, retrying in ${c}ms...`),await Rt(c)}})])}import{uniqueBy as $t}from"@latticexyz/common/utils";async function I({client:e,deployerAddress:o,contracts:n}){let t=$t(n,s=>s.bytecode),r=(await Promise.all(t.map(s=>Be({client:e,deployerAddress:o,...s})))).flat();if(r.length){l("waiting for contracts");for(let s of r)await Ht(e,{hash:s})}return r}import Ee from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import zt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{getCreate2Address as Nt,encodeDeployData as Lt,size as Vt}from"viem";import Me from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import je from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Re from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import He 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 Et from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{getCreate2Address as L,encodeDeployData as Ft,size as V}from"viem";function X(e){let o=V(Me.deployedBytecode.object),n=Me.bytecode.object,t=L({from:e,bytecode:n,salt:S}),r=V(je.deployedBytecode.object),s=je.bytecode.object,i=L({from:e,bytecode:s,salt:S}),a=V(Re.deployedBytecode.object),c=Re.bytecode.object,d=L({from:e,bytecode:c,salt:S}),f=V(He.deployedBytecode.object),u=He.bytecode.object,p=L({from:e,bytecode:u,salt:S}),g=V($e.deployedBytecode.object),h=Ft({bytecode:$e.bytecode.object,abi:Et,args:[t,i,d,p]}),w=L({from:e,bytecode:h,salt:S});return{AccessManagementSystem:{bytecode:n,deployedBytecodeSize:o,label:"access management system",address:t},BalanceTransferSystem:{bytecode:s,deployedBytecodeSize:r,label:"balance transfer system",address:i},BatchCallSystem:{bytecode:c,deployedBytecodeSize:a,label:"batch call system",address:d},RegistrationSystem:{bytecode:u,deployedBytecodeSize:f,label:"core registration system",address:p},InitModule:{bytecode:h,deployedBytecodeSize:g,label:"core module",address:w}}}function ee(e){let o=X(e),n=Vt(Ee.deployedBytecode.object),t=Lt({bytecode:Ee.bytecode.object,abi:zt,args:[o.InitModule.address]}),r=Nt({from:e,bytecode:t,salt:S});return{...o,WorldFactory:{bytecode:t,deployedBytecodeSize:n,label:"world factory",address:r}}}import Fe 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{getCreate2Address as _t,encodeDeployData as Kt,size as Jt}from"viem";function oe(e){let o=X(e),n=Jt(Fe.deployedBytecode.object),t=Kt({bytecode:Fe.bytecode.object,abi:Ut,args:[o.InitModule.address]}),r=_t({from:e,bytecode:t,salt:S});return{...o,WorldProxyFactory:{bytecode:t,deployedBytecodeSize:n,label:"world proxy factory",address:r}}}async function te(e,o,n){if(n){let r=oe(o);return await I({client:e,deployerAddress:o,contracts:Object.values(r)}),r.WorldProxyFactory.address}let t=ee(o);return await I({client:e,deployerAddress:o,contracts:Object.values(t)}),t.WorldFactory.address}import Xt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as er}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as qt,decodeEventLog as Yt,hexToString as ze,parseAbi as Gt}from"viem";import{isDefined as Qt}from"@latticexyz/common/utils";function re(e){let o=e.map(i=>{try{return{...i,...Yt({strict:!0,abi:Gt(Z),topics:i.topics,data:i.data})}}catch(a){if(a instanceof qt)return;throw a}}).filter(Qt),{address:n,deployBlock:t,worldVersion:r,storeVersion:s}=o.reduce((i,a)=>({...i,address:a.address,deployBlock:a.blockNumber,...a.eventName==="HelloWorld"?{worldVersion:ze(a.args.worldVersion).replace(/\0+$/,"")}:null,...a.eventName==="HelloStore"?{storeVersion:ze(a.args.storeVersion).replace(/\0+$/,"")}:null}),{});if(n==null)throw new Error("could not find world address");if(t==null)throw new Error("could not find world deploy block number");if(r==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:n,deployBlock:t,worldVersion:r,storeVersion:s}}async function Ne(e,o,n,t){let r=await te(e,o,t);l("deploying world");let s=await er(e,{chain:e.chain??null,address:r,abi:Xt,functionName:"deployWorld",args:[n]});l("waiting for world deploy");let i=await Zt(e,{hash:s});if(i.status!=="success")throw console.error("world deploy failed",i),new Error("world deploy failed");let a=re(i.logs);return l("deployed world to",a.address,"at block",a.deployBlock),{...a,stateBlock:a.deployBlock}}import{resourceToLabel as me,writeContract as ir}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as cr,keySchemaToHex as dr,valueSchemaToHex as lr}from"@latticexyz/protocol-parser/internal";import{parseAbiItem as or,decodeAbiParameters as Le,parseAbiParameters as Ve}from"viem";import{hexToResource as tr}from"@latticexyz/common";import{storeSetRecordEvent as rr}from"@latticexyz/store";import{getLogs as nr}from"viem/actions";import{decodeKey as sr,decodeValueArgs as ar,hexToSchema as Ue}from"@latticexyz/protocol-parser/internal";async function _e({client:e,worldDeploy:o}){l("looking up tables for",o.address);let t=(await nr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:or(rr),args:{tableId:j.store_Tables.tableId}})).map(r=>{let{tableId:s}=sr(j.store_Tables.keySchema,r.args.keyTuple),{namespace:i,name:a}=tr(s),c=ar(j.store_Tables.valueSchema,r.args),d=Ue(c.keySchema),f=Ue(c.valueSchema),u=Le(Ve("string[]"),c.abiEncodedKeyNames)[0],p=Le(Ve("string[]"),c.abiEncodedFieldNames)[0],g=[...f.staticFields,...f.dynamicFields],h=Object.fromEntries(d.staticFields.map((y,x)=>[u[x],y])),w=Object.fromEntries(g.map((y,x)=>[p[x],y]));return{namespace:i,name:a,tableId:s,keySchema:h,valueSchema:w}});return l("found",t.length,"tables for",o.address),t}import mr from"p-retry";import{wait as pr}from"@latticexyz/common/utils";async function Ke({client:e,worldDeploy:o,tables:n}){let r=(await _e({client:e,worldDeploy:o})).map(a=>a.tableId),s=n.filter(a=>r.includes(a.tableId));s.length&&l("existing tables",s.map(me).join(", "));let i=n.filter(a=>!r.includes(a.tableId));return i.length?(l("registering tables",i.map(me).join(", ")),await Promise.all(i.map(a=>mr(()=>ir(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerTable",args:[a.tableId,cr(a.valueSchema),dr(a.keySchema),lr(a.valueSchema),Object.keys(a.keySchema),Object.keys(a.valueSchema)]}),{retries:3,onFailedAttempt:async c=>{let d=c.attemptNumber*500;l(`failed to register table ${me(a)}, retrying in ${d}ms...`),await pr(d)}})))):[]}import{getAddress as W}from"viem";import{writeContract as pe,resourceToLabel as U}from"@latticexyz/common";import{parseAbiItem as fr,HttpRequestError as yr}from"viem";import{getLogs as ur}from"viem/actions";import{storeSpliceStaticDataEvent as gr}from"@latticexyz/store";import br from"p-retry";async function ne({client:e,worldDeploy:o}){l("looking up resource IDs for",o.address);let t=(await br(()=>ur(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:fr(gr),args:{tableId:j.store_ResourceIds.tableId}}),{retries:3,onFailedAttempt:async r=>{if(!(r instanceof yr&&r.status===400&&r.message.includes("block is out of range")))throw r}})).map(r=>r.args.keyTuple[0]);return l("found",t.length,"resource IDs for",o.address),t}import{hexToResource as Ar,resourceToLabel as kr}from"@latticexyz/common";import{decodeValueArgs as hr,encodeKey as wr}from"@latticexyz/protocol-parser/internal";import{readContract as xr}from"viem/actions";async function R({client:e,worldDeploy:o,table:n,key:t}){let[r,s,i]=await xr(e,{blockNumber:o.stateBlock,address:o.address,abi:v,functionName:"getRecord",args:[n.tableId,wr(n.keySchema,t)]});return hr(n.valueSchema,{staticData:r,encodedLengths:s,dynamicData:i})}import{parseAbiItem as Je}from"viem";import{storeSetRecordEvent as qe}from"@latticexyz/store";import{getLogs as Ye}from"viem/actions";import{decodeKey as Ge,decodeValueArgs as Qe}from"@latticexyz/protocol-parser/internal";async function se({client:e,worldDeploy:o}){l("looking up function selectors for",o.address);let t=(await Ye(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Je(qe),args:{tableId:D.world_FunctionSelectors.tableId}})).map(a=>({...Qe(D.world_FunctionSelectors.valueSchema,a.args),...Ge(D.world_FunctionSelectors.keySchema,a.args.keyTuple)}));l("found",t.length,"function selectors for",o.address),l("looking up function signatures for",o.address);let r=await Ye(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Je(qe),args:{tableId:D.world_FunctionSignatures.tableId}}),s=Object.fromEntries(r.map(a=>[Ge(D.world_FunctionSignatures.keySchema,a.args.keyTuple).functionSelector,Qe(D.world_FunctionSignatures.valueSchema,a.args).functionSignature]));return l("found",r.length,"function signatures for",o.address),t.map(({worldFunctionSelector:a,systemFunctionSelector:c,systemId:d})=>({selector:a,signature:s[a],systemFunctionSelector:c,systemFunctionSignature:s[c],systemId:d}))}import{parseAbiItem as Sr,getAddress as Cr}from"viem";import{storeSpliceStaticDataEvent as Dr}from"@latticexyz/store";import{getLogs as vr}from"viem/actions";import{decodeKey as Tr}from"@latticexyz/protocol-parser/internal";async function ae({client:e,worldDeploy:o}){l("looking up resource access for",o.address);let t=(await vr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Sr(Dr),args:{tableId:D.world_ResourceAccess.tableId}})).map(s=>Tr(D.world_ResourceAccess.keySchema,s.args.keyTuple)),r=(await Promise.all(t.map(async s=>[s,await R({client:e,worldDeploy:o,table:D.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Cr(s.caller)}));return l("found",r.length,"resource<>address access pairs"),r}async function Ze({client:e,worldDeploy:o}){let[n,t,r]=await Promise.all([ne({client:e,worldDeploy:o}),se({client:e,worldDeploy:o}),ae({client:e,worldDeploy:o})]),s=n.map(Ar).filter(i=>i.type==="system");return l("looking up systems",s.map(kr).join(", ")),await Promise.all(s.map(async i=>{let{system:a,publicAccess:c}=await R({client:e,worldDeploy:o,table:D.world_Systems,key:{systemId:i.resourceId}}),d=t.filter(f=>f.systemId===i.resourceId);return{address:a,namespace:i.namespace,name:i.name,systemId:i.resourceId,allowAll:c,allowedAddresses:r.filter(({resourceId:f})=>f===i.resourceId).map(({address:f})=>f),functions:d}}))}import{wait as fe}from"@latticexyz/common/utils";import ye from"p-retry";async function Xe({client:e,deployerAddress:o,libraries:n,worldDeploy:t,systems:r}){let[s,i]=await Promise.all([Ze({client:e,worldDeploy:t}),ae({client:e,worldDeploy:t})]),a=r.filter(m=>s.some(b=>b.systemId===m.systemId&&W(b.address)===W(m.prepareDeploy(o,n).address)));a.length&&l("existing systems",a.map(U).join(", "));let c=a.map(m=>m.systemId),d=r.filter(m=>!c.includes(m.systemId));if(!d.length)return[];let f=d.filter(m=>s.some(b=>b.systemId===m.systemId&&W(b.address)!==W(m.prepareDeploy(o,n).address)));f.length&&l("upgrading systems",f.map(U).join(", "));let u=d.filter(m=>!s.some(b=>b.systemId===m.systemId));u.length&&l("registering new systems",u.map(U).join(", ")),await I({client:e,deployerAddress:o,contracts:d.map(m=>({bytecode:m.prepareDeploy(o,n).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${U(m)} system`}))});let p=await Promise.all(d.map(m=>ye(()=>pe(e,{chain:e.chain??null,address:t.address,abi:v,functionName:"registerSystem",args:[m.systemId,m.prepareDeploy(o,n).address,m.allowAll]}),{retries:3,onFailedAttempt:async b=>{let C=b.attemptNumber*500;l(`failed to register system ${U(m)}, retrying in ${C}ms...`),await fe(C)}}))),g=r.map(m=>m.systemId),h=i.filter(({resourceId:m})=>g.includes(m)),w=[...r.flatMap(m=>m.allowedAddresses.map(b=>({resourceId:m.systemId,address:b}))),...r.flatMap(m=>m.allowedSystemIds.map(b=>({resourceId:m.systemId,address:s.find(C=>C.systemId===b)?.address??r.find(C=>C.systemId===b)?.prepareDeploy(o,n).address})).filter(b=>b.address!=null))],y=w.filter(m=>!h.some(({resourceId:b,address:C})=>b===m.resourceId&&W(C)===W(m.address))),x=h.filter(m=>!w.some(({resourceId:b,address:C})=>b===m.resourceId&&W(C)===W(m.address)));x.length&&l("revoking",x.length,"access grants"),y.length&&l("adding",y.length,"access grants");let T=await Promise.all([...x.map(m=>ye(()=>pe(e,{chain:e.chain??null,address:t.address,abi:v,functionName:"revokeAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:async b=>{let C=b.attemptNumber*500;l(`failed to revoke access, retrying in ${C}ms...`),await fe(C)}})),...y.map(m=>ye(()=>pe(e,{chain:e.chain??null,address:t.address,abi:v,functionName:"grantAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:async b=>{let C=b.attemptNumber*500;l(`failed to grant access, retrying in ${C}ms...`),await fe(C)}}))]);return[...p,...T]}import{waitForTransactionReceipt as fo}from"viem/actions";import{getAddress as Pr,parseAbi as Ir}from"viem";import{getBlockNumber as Or,getLogs as Wr}from"viem/actions";var eo=new Map;async function oo(e,o){let n=Pr(o),t=eo.get(n);if(t!=null)return t;l("looking up world deploy for",n);let r=await Or(e),s=await Wr(e,{strict:!0,address:n,events:Ir(Z),fromBlock:"earliest",toBlock:r});return t={...re(s),stateBlock:r},eo.set(n,t),l("found world deploy for",n,"at block",t.deployBlock),t}import{hexToResource as Br,writeContract as to}from"@latticexyz/common";import ro from"p-retry";import{wait as no}from"@latticexyz/common/utils";async function so({client:e,worldDeploy:o,functions:n}){let t=await se({client:e,worldDeploy:o}),r=Object.fromEntries(t.map(a=>[a.selector,a])),s=n.filter(a=>r[a.selector]),i=n.filter(a=>!s.includes(a));if(s.length){l("functions already registered:",s.map(c=>c.signature).join(", "));let a=s.filter(c=>c.systemId!==r[c.selector]?.systemId);a.length&&console.warn("found",a.length,"functions already registered but pointing at a different system ID:",a.map(c=>c.signature).join(", "))}return i.length?(l("registering functions:",i.map(a=>a.signature).join(", ")),Promise.all(i.map(a=>{let{namespace:c}=Br(a.systemId);return c===""?ro(()=>to(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerRootFunctionSelector",args:[a.systemId,a.systemFunctionSignature,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async d=>{let f=d.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await no(f)}}):ro(()=>to(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerFunctionSelector",args:[a.systemId,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async d=>{let f=d.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await no(f)}})}))):[]}import{BaseError as Mr}from"viem";import{writeContract as ao}from"@latticexyz/common";import{isDefined as jr,wait as Rr}from"@latticexyz/common/utils";import Hr from"p-retry";async function io({client:e,deployerAddress:o,libraries:n,worldDeploy:t,modules:r}){return r.length?(await I({client:e,deployerAddress:o,contracts:r.map(s=>({bytecode:s.prepareDeploy(o,n).bytecode,deployedBytecodeSize:s.deployedBytecodeSize,label:`${s.name} module`}))}),l("installing modules:",r.map(s=>s.name).join(", ")),(await Promise.all(r.map(s=>Hr(async()=>{try{let i=[...v,...s.abi],a=s.prepareDeploy(o,n).address;return s.installAsRoot?await ao(e,{chain:e.chain??null,address:t.address,abi:i,functionName:"installRootModule",args:[a,s.installData]}):await ao(e,{chain:e.chain??null,address:t.address,abi:i,functionName:"installModule",args:[a,s.installData]})}catch(i){if(i instanceof Mr&&i.message.includes("Module_AlreadyInstalled")){l(`module ${s.name} already installed`);return}throw i}},{retries:3,onFailedAttempt:async i=>{let a=i.attemptNumber*500;l(`failed to install module ${s.name}, retrying in ${a}ms...`),await Rr(a)}})))).filter(jr)):[]}import{getAddress as co}from"viem";import{hexToResource as lo,resourceToHex as mo,writeContract as $r}from"@latticexyz/common";async function po({client:e,worldDeploy:o,resourceIds:n}){let t=Array.from(new Set(n.map(u=>lo(u).namespace))),r=await ne({client:e,worldDeploy:o}),s=new Set(r.map(u=>lo(u).namespace));s.size&&l("found",s.size,"existing namespaces:",Array.from(s).map(u=>u===""?"<root>":u).join(", "));let i=t.filter(u=>s.has(u)),c=(await Promise.all(i.map(async u=>{let{owner:p}=await R({client:e,worldDeploy:o,table:D.world_NamespaceOwner,key:{namespaceId:mo({type:"namespace",namespace:u,name:""})}});return[u,p]}))).filter(([,u])=>co(u)!==co(e.account.address)).map(([u])=>u);if(c.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${c.join(", ")}`);let d=t.filter(u=>!s.has(u));return d.length>0&&l("registering namespaces",Array.from(d).join(", ")),Promise.all(d.map(u=>$r(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerNamespace",args:[mo({namespace:u,type:"namespace",name:""})]})))}import{resourceToLabel as Er}from"@latticexyz/common";import{randomBytes as Fr}from"crypto";async function yo({client:e,config:o,modules:n=[],salt:t,worldAddress:r,deployerAddress:s,withWorldProxy:i}){let a=Object.values(o.tables),c=s??await Pe(e);await te(e,c,i),await I({client:e,deployerAddress:c,contracts:[...o.libraries.map(y=>({bytecode:y.prepareDeploy(c,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${y.path}:${y.name} library`})),...o.systems.map(y=>({bytecode:y.prepareDeploy(c,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${Er(y)} system`})),...n.map(y=>({bytecode:y.prepareDeploy(c,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${y.name} module`}))]});let d=r?await oo(e,r):await Ne(e,c,t??`0x${Fr(32).toString("hex")}`,i);if(!Oe.includes(d.storeVersion))throw new Error(`Unsupported Store version: ${d.storeVersion}`);if(!We.includes(d.worldVersion))throw new Error(`Unsupported World version: ${d.worldVersion}`);let f=await po({client:e,worldDeploy:d,resourceIds:[...a.map(y=>y.tableId),...o.systems.map(y=>y.systemId)]});l("waiting for all namespace registration transactions to confirm");for(let y of f)await fo(e,{hash:y});let u=await Ke({client:e,worldDeploy:d,tables:a}),p=await Xe({client:e,deployerAddress:c,libraries:o.libraries,worldDeploy:d,systems:o.systems}),g=await so({client:e,worldDeploy:d,functions:o.systems.flatMap(y=>y.functions)}),h=await io({client:e,deployerAddress:c,libraries:o.libraries,worldDeploy:d,modules:n}),w=[...u,...p,...g,...h];l("waiting for all transactions to confirm");for(let y of w)await fo(e,{hash:y});return l("deploy complete"),d}import{createWalletClient as un,http as gn,isHex as bn}from"viem";import{privateKeyToAccount as hn}from"viem/accounts";import{loadConfig as wn,resolveConfigPath as xn}from"@latticexyz/config/node";import{worldToV1 as Sn}from"@latticexyz/world/config/v2";import{getOutDirectory as Cn,getRpcUrl as Dn,getSrcDirectory as vn}from"@latticexyz/common/foundry";import $ from"chalk";import{MUDError as be}from"@latticexyz/common/errors";import qr from"path";import{resolveWorldConfig as Yr}from"@latticexyz/world/internal";import{resourceToHex as bo}from"@latticexyz/common";import{toFunctionSelector as ho,toFunctionSignature as wo}from"viem";import{readFileSync as zr}from"fs";import Nr from"path";import{MUDError as ce}from"@latticexyz/common/errors";import{size as Lr}from"viem";function ie(e){return Object.entries(e).flatMap(([o,n])=>Object.entries(n).flatMap(([t,r])=>r.map(s=>({path:o,name:t,start:s.start,length:s.length}))))}function H(e,o,n){let t,r=Nr.join(n,e,o+".json");try{t=JSON.parse(zr(r,"utf8"))}catch{throw new ce(`Error reading file at ${r}`)}let s=t?.bytecode?.object;if(!s)throw new ce(`No bytecode found in ${r}`);let i=t?.deployedBytecode?.object;if(!i)throw new ce(`No deployed bytecode found in ${r}`);let a=t?.abi;if(!a)throw new ce(`No ABI found in ${r}`);let c=ie(t?.bytecode?.linkReferences??{});return{abi:a,bytecode:s,placeholders:c,deployedBytecodeSize:Lr(i)}}import{groupBy as Gr}from"@latticexyz/common/utils";import{readFileSync as Ur}from"fs";import _r from"glob";import Vr from"toposort";function uo(e,o,n){let t=Vr(e.flatMap(r=>n(r).map(s=>[o(r),s])));return[...e].sort((r,s)=>t.indexOf(o(r))-t.indexOf(o(s)))}function go(e){let n=_r.sync(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).map(t=>JSON.parse(Ur(t,"utf8"))).flatMap(t=>{if(!t.metadata)return[];let r=Object.keys(t.metadata.settings.compilationTarget)[0],s=t.metadata.settings.compilationTarget[r],i=t.bytecode.linkReferences;return Object.entries(i).flatMap(([a,c])=>Object.keys(c).map(d=>({path:a,name:d,dependentPath:r,dependentName:s})))});return uo(n,t=>`${t.path}:${t.name}`,t=>[`${t.dependentPath}:${t.dependentName}`])}import{spliceHex as Kr}from"@latticexyz/common";import{getCreate2Address as Jr}from"viem";function _(e,o){return function(t,r){let s=e;for(let i of o){let a=r.find(c=>c.path===i.path&&c.name===i.name);if(!a)throw new Error(`Could not find library for bytecode placeholder ${i.path}:${i.name}`);s=Kr(s,i.start,i.length,a.prepareDeploy(t,r).address)}return{bytecode:s,address:Jr({from:t,bytecode:s,salt:S})}}}function xo({config:e,forgeSourceDir:o,forgeOutDir:n}){let t=go(n).map(p=>{let g=H(qr.basename(p.path),p.name,n);return{path:p.path,name:p.name,abi:g.abi,prepareDeploy:_(g.bytecode,g.placeholders),deployedBytecodeSize:g.deployedBytecodeSize}}),r=z(e),s=k(o).map(({basename:p})=>p),i=Yr(e,s),c=H("System.sol","System",n).abi.filter(p=>p.type==="function").map(wo),d=Object.entries(i.systems).map(([p,g])=>{let h=e.namespace,w=g.name,y=bo({type:"system",namespace:h,name:w}),x=H(`${p}.sol`,p,n),T=x.abi.filter(m=>m.type==="function").map(wo).filter(m=>!c.includes(m)).map(m=>{let b=h===""?m:`${h}__${m}`;return{signature:b,selector:ho(b),systemId:y,systemFunctionSignature:m,systemFunctionSelector:ho(m)}});return{namespace:h,name:w,systemId:y,allowAll:g.openAccess,allowedAddresses:g.accessListAddresses,allowedSystemIds:g.accessListSystems.map(m=>bo({type:"system",namespace:h,name:i.systems[m].name})),prepareDeploy:_(x.bytecode,x.placeholders),deployedBytecodeSize:x.deployedBytecodeSize,abi:x.abi,functions:T}}),f=Gr(d,p=>p.systemId),u=Array.from(f.values()).filter(p=>p.length>1).flat();if(u.length){let p=u.map(g=>g.name);throw new Error(`Found systems with overlapping system ID: ${p.join(", ")}.
13
+ `),l("deploying",r,"at",s),[await jt(()=>Mt(e,{chain:e.chain??null,to:o,data:Ot([S,n])}),{retries:3,onFailedAttempt:async a=>{let c=a.attemptNumber*500;l(`failed to deploy ${r}, retrying in ${c}ms...`),await Rt(c)}})])}import{uniqueBy as $t}from"@latticexyz/common/utils";async function I({client:e,deployerAddress:o,contracts:n}){let t=$t(n,s=>s.bytecode),r=(await Promise.all(t.map(s=>Be({client:e,deployerAddress:o,...s})))).flat();if(r.length){l("waiting for contracts");for(let s of r)await Ht(e,{hash:s})}return r}import Ee from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import zt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{getCreate2Address as Nt,encodeDeployData as Lt,size as Vt}from"viem";import Me from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import je from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Re from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import He 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 Et from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{getCreate2Address as L,encodeDeployData as Ft,size as V}from"viem";function X(e){let o=V(Me.deployedBytecode.object),n=Me.bytecode.object,t=L({from:e,bytecode:n,salt:S}),r=V(je.deployedBytecode.object),s=je.bytecode.object,i=L({from:e,bytecode:s,salt:S}),a=V(Re.deployedBytecode.object),c=Re.bytecode.object,d=L({from:e,bytecode:c,salt:S}),f=V(He.deployedBytecode.object),u=He.bytecode.object,p=L({from:e,bytecode:u,salt:S}),g=V($e.deployedBytecode.object),h=Ft({bytecode:$e.bytecode.object,abi:Et,args:[t,i,d,p]}),w=L({from:e,bytecode:h,salt:S});return{AccessManagementSystem:{bytecode:n,deployedBytecodeSize:o,label:"access management system",address:t},BalanceTransferSystem:{bytecode:s,deployedBytecodeSize:r,label:"balance transfer system",address:i},BatchCallSystem:{bytecode:c,deployedBytecodeSize:a,label:"batch call system",address:d},RegistrationSystem:{bytecode:u,deployedBytecodeSize:f,label:"core registration system",address:p},InitModule:{bytecode:h,deployedBytecodeSize:g,label:"core module",address:w}}}function ee(e){let o=X(e),n=Vt(Ee.deployedBytecode.object),t=Lt({bytecode:Ee.bytecode.object,abi:zt,args:[o.InitModule.address]}),r=Nt({from:e,bytecode:t,salt:S});return{...o,WorldFactory:{bytecode:t,deployedBytecodeSize:n,label:"world factory",address:r}}}import Fe 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{getCreate2Address as _t,encodeDeployData as Kt,size as Jt}from"viem";function oe(e){let o=X(e),n=Jt(Fe.deployedBytecode.object),t=Kt({bytecode:Fe.bytecode.object,abi:Ut,args:[o.InitModule.address]}),r=_t({from:e,bytecode:t,salt:S});return{...o,WorldProxyFactory:{bytecode:t,deployedBytecodeSize:n,label:"world proxy factory",address:r}}}async function te(e,o,n){if(n){let r=oe(o);return await I({client:e,deployerAddress:o,contracts:Object.values(r)}),r.WorldProxyFactory.address}let t=ee(o);return await I({client:e,deployerAddress:o,contracts:Object.values(t)}),t.WorldFactory.address}import Xt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as er}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as qt,decodeEventLog as Yt,hexToString as ze,parseAbi as Gt}from"viem";import{isDefined as Qt}from"@latticexyz/common/utils";function re(e){let o=e.map(i=>{try{return{...i,...Yt({strict:!0,abi:Gt(Z),topics:i.topics,data:i.data})}}catch(a){if(a instanceof qt)return;throw a}}).filter(Qt),{address:n,deployBlock:t,worldVersion:r,storeVersion:s}=o.reduce((i,a)=>({...i,address:a.address,deployBlock:a.blockNumber,...a.eventName==="HelloWorld"?{worldVersion:ze(a.args.worldVersion).replace(/\0+$/,"")}:null,...a.eventName==="HelloStore"?{storeVersion:ze(a.args.storeVersion).replace(/\0+$/,"")}:null}),{});if(n==null)throw new Error("could not find world address");if(t==null)throw new Error("could not find world deploy block number");if(r==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:n,deployBlock:t,worldVersion:r,storeVersion:s}}async function Ne(e,o,n,t){let r=await te(e,o,t);l("deploying world");let s=await er(e,{chain:e.chain??null,address:r,abi:Xt,functionName:"deployWorld",args:[n]});l("waiting for world deploy");let i=await Zt(e,{hash:s});if(i.status!=="success")throw console.error("world deploy failed",i),new Error("world deploy failed");let a=re(i.logs);return l("deployed world to",a.address,"at block",a.deployBlock),{...a,stateBlock:a.deployBlock}}import{resourceToLabel as me,writeContract as ir}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as cr,keySchemaToHex as dr,valueSchemaToHex as lr}from"@latticexyz/protocol-parser/internal";import{parseAbiItem as or,decodeAbiParameters as Le,parseAbiParameters as Ve}from"viem";import{hexToResource as tr}from"@latticexyz/common";import{storeSetRecordEvent as rr}from"@latticexyz/store";import{getLogs as nr}from"viem/actions";import{decodeKey as sr,decodeValueArgs as ar,hexToSchema as Ue}from"@latticexyz/protocol-parser/internal";async function _e({client:e,worldDeploy:o}){l("looking up tables for",o.address);let t=(await nr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:or(rr),args:{tableId:j.store_Tables.tableId}})).map(r=>{let{tableId:s}=sr(j.store_Tables.keySchema,r.args.keyTuple),{namespace:i,name:a}=tr(s),c=ar(j.store_Tables.valueSchema,r.args),d=Ue(c.keySchema),f=Ue(c.valueSchema),u=Le(Ve("string[]"),c.abiEncodedKeyNames)[0],p=Le(Ve("string[]"),c.abiEncodedFieldNames)[0],g=[...f.staticFields,...f.dynamicFields],h=Object.fromEntries(d.staticFields.map((y,x)=>[u[x],y])),w=Object.fromEntries(g.map((y,x)=>[p[x],y]));return{namespace:i,name:a,tableId:s,keySchema:h,valueSchema:w}});return l("found",t.length,"tables for",o.address),t}import mr from"p-retry";import{wait as pr}from"@latticexyz/common/utils";async function Ke({client:e,worldDeploy:o,tables:n}){let r=(await _e({client:e,worldDeploy:o})).map(a=>a.tableId),s=n.filter(a=>r.includes(a.tableId));s.length&&l("existing tables",s.map(me).join(", "));let i=n.filter(a=>!r.includes(a.tableId));return i.length?(l("registering tables",i.map(me).join(", ")),await Promise.all(i.map(a=>mr(()=>ir(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerTable",args:[a.tableId,cr(a.valueSchema),dr(a.keySchema),lr(a.valueSchema),Object.keys(a.keySchema),Object.keys(a.valueSchema)]}),{retries:3,onFailedAttempt:async c=>{let d=c.attemptNumber*500;l(`failed to register table ${me(a)}, retrying in ${d}ms...`),await pr(d)}})))):[]}import{getAddress as W}from"viem";import{writeContract as pe,resourceToLabel as U}from"@latticexyz/common";import{parseAbiItem as fr,HttpRequestError as yr}from"viem";import{getLogs as ur}from"viem/actions";import{storeSpliceStaticDataEvent as gr}from"@latticexyz/store";import br from"p-retry";async function ne({client:e,worldDeploy:o}){l("looking up resource IDs for",o.address);let t=(await br(()=>ur(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:fr(gr),args:{tableId:j.store_ResourceIds.tableId}}),{retries:3,onFailedAttempt:async r=>{if(!(r instanceof yr&&r.status===400&&r.message.includes("block is out of range")))throw r}})).map(r=>r.args.keyTuple[0]);return l("found",t.length,"resource IDs for",o.address),t}import{hexToResource as Ar,resourceToLabel as kr}from"@latticexyz/common";import{decodeValueArgs as hr,encodeKey as wr}from"@latticexyz/protocol-parser/internal";import{readContract as xr}from"viem/actions";async function R({client:e,worldDeploy:o,table:n,key:t}){let[r,s,i]=await xr(e,{blockNumber:o.stateBlock,address:o.address,abi:v,functionName:"getRecord",args:[n.tableId,wr(n.keySchema,t)]});return hr(n.valueSchema,{staticData:r,encodedLengths:s,dynamicData:i})}import{parseAbiItem as Je}from"viem";import{storeSetRecordEvent as qe}from"@latticexyz/store";import{getLogs as Ye}from"viem/actions";import{decodeKey as Ge,decodeValueArgs as Qe}from"@latticexyz/protocol-parser/internal";async function se({client:e,worldDeploy:o}){l("looking up function selectors for",o.address);let t=(await Ye(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Je(qe),args:{tableId:D.world_FunctionSelectors.tableId}})).map(a=>({...Qe(D.world_FunctionSelectors.valueSchema,a.args),...Ge(D.world_FunctionSelectors.keySchema,a.args.keyTuple)}));l("found",t.length,"function selectors for",o.address),l("looking up function signatures for",o.address);let r=await Ye(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Je(qe),args:{tableId:D.world_FunctionSignatures.tableId}}),s=Object.fromEntries(r.map(a=>[Ge(D.world_FunctionSignatures.keySchema,a.args.keyTuple).functionSelector,Qe(D.world_FunctionSignatures.valueSchema,a.args).functionSignature]));return l("found",r.length,"function signatures for",o.address),t.map(({worldFunctionSelector:a,systemFunctionSelector:c,systemId:d})=>({selector:a,signature:s[a],systemFunctionSelector:c,systemFunctionSignature:s[c],systemId:d}))}import{parseAbiItem as Sr,getAddress as Cr}from"viem";import{storeSpliceStaticDataEvent as Dr}from"@latticexyz/store";import{getLogs as vr}from"viem/actions";import{decodeKey as Tr}from"@latticexyz/protocol-parser/internal";async function ae({client:e,worldDeploy:o}){l("looking up resource access for",o.address);let t=(await vr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Sr(Dr),args:{tableId:D.world_ResourceAccess.tableId}})).map(s=>Tr(D.world_ResourceAccess.keySchema,s.args.keyTuple)),r=(await Promise.all(t.map(async s=>[s,await R({client:e,worldDeploy:o,table:D.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:Cr(s.caller)}));return l("found",r.length,"resource<>address access pairs"),r}async function Ze({client:e,worldDeploy:o}){let[n,t,r]=await Promise.all([ne({client:e,worldDeploy:o}),se({client:e,worldDeploy:o}),ae({client:e,worldDeploy:o})]),s=n.map(Ar).filter(i=>i.type==="system");return l("looking up systems",s.map(kr).join(", ")),await Promise.all(s.map(async i=>{let{system:a,publicAccess:c}=await R({client:e,worldDeploy:o,table:D.world_Systems,key:{systemId:i.resourceId}}),d=t.filter(f=>f.systemId===i.resourceId);return{address:a,namespace:i.namespace,name:i.name,systemId:i.resourceId,allowAll:c,allowedAddresses:r.filter(({resourceId:f})=>f===i.resourceId).map(({address:f})=>f),functions:d}}))}import{wait as fe}from"@latticexyz/common/utils";import ye from"p-retry";async function Xe({client:e,deployerAddress:o,libraries:n,worldDeploy:t,systems:r}){let[s,i]=await Promise.all([Ze({client:e,worldDeploy:t}),ae({client:e,worldDeploy:t})]),a=r.filter(m=>s.some(b=>b.systemId===m.systemId&&W(b.address)===W(m.prepareDeploy(o,n).address)));a.length&&l("existing systems",a.map(U).join(", "));let c=a.map(m=>m.systemId),d=r.filter(m=>!c.includes(m.systemId));if(!d.length)return[];let f=d.filter(m=>s.some(b=>b.systemId===m.systemId&&W(b.address)!==W(m.prepareDeploy(o,n).address)));f.length&&l("upgrading systems",f.map(U).join(", "));let u=d.filter(m=>!s.some(b=>b.systemId===m.systemId));u.length&&l("registering new systems",u.map(U).join(", ")),await I({client:e,deployerAddress:o,contracts:d.map(m=>({bytecode:m.prepareDeploy(o,n).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${U(m)} system`}))});let p=await Promise.all(d.map(m=>ye(()=>pe(e,{chain:e.chain??null,address:t.address,abi:v,functionName:"registerSystem",args:[m.systemId,m.prepareDeploy(o,n).address,m.allowAll]}),{retries:3,onFailedAttempt:async b=>{let C=b.attemptNumber*500;l(`failed to register system ${U(m)}, retrying in ${C}ms...`),await fe(C)}}))),g=r.map(m=>m.systemId),h=i.filter(({resourceId:m})=>g.includes(m)),w=[...r.flatMap(m=>m.allowedAddresses.map(b=>({resourceId:m.systemId,address:b}))),...r.flatMap(m=>m.allowedSystemIds.map(b=>({resourceId:m.systemId,address:s.find(C=>C.systemId===b)?.address??r.find(C=>C.systemId===b)?.prepareDeploy(o,n).address})).filter(b=>b.address!=null))],y=w.filter(m=>!h.some(({resourceId:b,address:C})=>b===m.resourceId&&W(C)===W(m.address))),x=h.filter(m=>!w.some(({resourceId:b,address:C})=>b===m.resourceId&&W(C)===W(m.address)));x.length&&l("revoking",x.length,"access grants"),y.length&&l("adding",y.length,"access grants");let T=await Promise.all([...x.map(m=>ye(()=>pe(e,{chain:e.chain??null,address:t.address,abi:v,functionName:"revokeAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:async b=>{let C=b.attemptNumber*500;l(`failed to revoke access, retrying in ${C}ms...`),await fe(C)}})),...y.map(m=>ye(()=>pe(e,{chain:e.chain??null,address:t.address,abi:v,functionName:"grantAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:async b=>{let C=b.attemptNumber*500;l(`failed to grant access, retrying in ${C}ms...`),await fe(C)}}))]);return[...p,...T]}import{waitForTransactionReceipt as fo}from"viem/actions";import{getAddress as Pr,parseAbi as Ir}from"viem";import{getBlockNumber as Or,getLogs as Wr}from"viem/actions";var eo=new Map;async function oo(e,o){let n=Pr(o),t=eo.get(n);if(t!=null)return t;l("looking up world deploy for",n);let r=await Or(e),s=await Wr(e,{strict:!0,address:n,events:Ir(Z),fromBlock:"earliest",toBlock:r});return t={...re(s),stateBlock:r},eo.set(n,t),l("found world deploy for",n,"at block",t.deployBlock),t}import{hexToResource as Br,writeContract as to}from"@latticexyz/common";import ro from"p-retry";import{wait as no}from"@latticexyz/common/utils";async function so({client:e,worldDeploy:o,functions:n}){let t=await se({client:e,worldDeploy:o}),r=Object.fromEntries(t.map(a=>[a.selector,a])),s=n.filter(a=>r[a.selector]),i=n.filter(a=>!s.includes(a));if(s.length){l("functions already registered:",s.map(c=>c.signature).join(", "));let a=s.filter(c=>c.systemId!==r[c.selector]?.systemId);a.length&&console.warn("found",a.length,"functions already registered but pointing at a different system ID:",a.map(c=>c.signature).join(", "))}return i.length?(l("registering functions:",i.map(a=>a.signature).join(", ")),Promise.all(i.map(a=>{let{namespace:c}=Br(a.systemId);return c===""?ro(()=>to(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerRootFunctionSelector",args:[a.systemId,a.systemFunctionSignature,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async d=>{let f=d.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await no(f)}}):ro(()=>to(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerFunctionSelector",args:[a.systemId,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async d=>{let f=d.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await no(f)}})}))):[]}import{BaseError as Mr}from"viem";import{writeContract as ao}from"@latticexyz/common";import{isDefined as jr,wait as Rr}from"@latticexyz/common/utils";import Hr from"p-retry";async function io({client:e,deployerAddress:o,libraries:n,worldDeploy:t,modules:r}){return r.length?(await I({client:e,deployerAddress:o,contracts:r.map(s=>({bytecode:s.prepareDeploy(o,n).bytecode,deployedBytecodeSize:s.deployedBytecodeSize,label:`${s.name} module`}))}),l("installing modules:",r.map(s=>s.name).join(", ")),(await Promise.all(r.map(s=>Hr(async()=>{try{let i=[...v,...s.abi],a=s.prepareDeploy(o,n).address;return s.installAsRoot?await ao(e,{chain:e.chain??null,address:t.address,abi:i,functionName:"installRootModule",args:[a,s.installData]}):await ao(e,{chain:e.chain??null,address:t.address,abi:i,functionName:"installModule",args:[a,s.installData]})}catch(i){if(i instanceof Mr&&i.message.includes("Module_AlreadyInstalled")){l(`module ${s.name} already installed`);return}throw i}},{retries:3,onFailedAttempt:async i=>{let a=i.attemptNumber*500;l(`failed to install module ${s.name}, retrying in ${a}ms...`),await Rr(a)}})))).filter(jr)):[]}import{getAddress as co}from"viem";import{hexToResource as lo,resourceToHex as mo,writeContract as $r}from"@latticexyz/common";async function po({client:e,worldDeploy:o,resourceIds:n}){let t=Array.from(new Set(n.map(u=>lo(u).namespace))),r=await ne({client:e,worldDeploy:o}),s=new Set(r.map(u=>lo(u).namespace));s.size&&l("found",s.size,"existing namespaces:",Array.from(s).map(u=>u===""?"<root>":u).join(", "));let i=t.filter(u=>s.has(u)),c=(await Promise.all(i.map(async u=>{let{owner:p}=await R({client:e,worldDeploy:o,table:D.world_NamespaceOwner,key:{namespaceId:mo({type:"namespace",namespace:u,name:""})}});return[u,p]}))).filter(([,u])=>co(u)!==co(e.account.address)).map(([u])=>u);if(c.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${c.join(", ")}`);let d=t.filter(u=>!s.has(u));return d.length>0&&l("registering namespaces",Array.from(d).join(", ")),Promise.all(d.map(u=>$r(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerNamespace",args:[mo({namespace:u,type:"namespace",name:""})]})))}import{resourceToLabel as Er}from"@latticexyz/common";import{randomBytes as Fr}from"crypto";async function yo({client:e,config:o,modules:n=[],salt:t,worldAddress:r,deployerAddress:s,withWorldProxy:i}){let a=Object.values(o.tables),c=s??await Pe(e);await te(e,c,i),await I({client:e,deployerAddress:c,contracts:[...o.libraries.map(y=>({bytecode:y.prepareDeploy(c,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${y.path}:${y.name} library`})),...o.systems.map(y=>({bytecode:y.prepareDeploy(c,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${Er(y)} system`})),...n.map(y=>({bytecode:y.prepareDeploy(c,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${y.name} module`}))]});let d=r?await oo(e,r):await Ne(e,c,t??`0x${Fr(32).toString("hex")}`,i);if(!Oe.includes(d.storeVersion))throw new Error(`Unsupported Store version: ${d.storeVersion}`);if(!We.includes(d.worldVersion))throw new Error(`Unsupported World version: ${d.worldVersion}`);let f=await po({client:e,worldDeploy:d,resourceIds:[...a.map(y=>y.tableId),...o.systems.map(y=>y.systemId)]});l("waiting for all namespace registration transactions to confirm");for(let y of f)await fo(e,{hash:y});let u=await Ke({client:e,worldDeploy:d,tables:a}),p=await Xe({client:e,deployerAddress:c,libraries:o.libraries,worldDeploy:d,systems:o.systems}),g=await so({client:e,worldDeploy:d,functions:o.systems.flatMap(y=>y.functions)}),h=await io({client:e,deployerAddress:c,libraries:o.libraries,worldDeploy:d,modules:n}),w=[...u,...p,...g,...h];l("waiting for all transactions to confirm");for(let y of w)await fo(e,{hash:y});return l("deploy complete"),d}import{createWalletClient as un,http as gn,isHex as bn}from"viem";import{privateKeyToAccount as hn}from"viem/accounts";import{loadConfig as wn,resolveConfigPath as xn}from"@latticexyz/config/node";import{worldToV1 as Sn}from"@latticexyz/world/config/v2";import{getOutDirectory as Cn,getRpcUrl as Dn,getSrcDirectory as vn}from"@latticexyz/common/foundry";import $ from"chalk";import{MUDError as be}from"@latticexyz/common/errors";import qr from"path";import{resolveWorldConfig as Yr}from"@latticexyz/world/internal";import{resourceToHex as bo}from"@latticexyz/common";import{toFunctionSelector as ho,toFunctionSignature as wo}from"viem";import{readFileSync as zr}from"fs";import Nr from"path";import{MUDError as ce}from"@latticexyz/common/errors";import{size as Lr}from"viem";function ie(e){return Object.entries(e).flatMap(([o,n])=>Object.entries(n).flatMap(([t,r])=>r.map(s=>({path:o,name:t,start:s.start,length:s.length}))))}function H(e,o,n){let t,r=Nr.join(n,e,o+".json");try{t=JSON.parse(zr(r,"utf8"))}catch{throw new ce(`Error reading file at ${r}`)}let s=t?.bytecode?.object;if(!s)throw new ce(`No bytecode found in ${r}`);let i=t?.deployedBytecode?.object;if(!i)throw new ce(`No deployed bytecode found in ${r}`);let a=t?.abi;if(!a)throw new ce(`No ABI found in ${r}`);let c=ie(t?.bytecode?.linkReferences??{});return{abi:a,bytecode:s,placeholders:c,deployedBytecodeSize:Lr(i)}}import{groupBy as Gr}from"@latticexyz/common/utils";import{readFileSync as Ur}from"fs";import _r from"glob";import Vr from"toposort";function uo(e,o,n){let t=Vr(e.flatMap(r=>n(r).map(s=>[o(r),s])));return[...e].sort((r,s)=>t.indexOf(o(r))-t.indexOf(o(s)))}function go(e){let n=_r.sync(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).map(t=>JSON.parse(Ur(t,"utf8"))).flatMap(t=>{if(!t.metadata)return[];let r=Object.keys(t.metadata.settings.compilationTarget)[0],s=t.metadata.settings.compilationTarget[r],i=t.bytecode.linkReferences;return Object.entries(i).flatMap(([a,c])=>Object.keys(c).map(d=>({path:a,name:d,dependentPath:r,dependentName:s})))});return uo(n,t=>`${t.path}:${t.name}`,t=>[`${t.dependentPath}:${t.dependentName}`])}import{spliceHex as Kr}from"@latticexyz/common";import{getCreate2Address as Jr}from"viem";function _(e,o){return function(t,r){let s=e;for(let i of o){let a=r.find(c=>c.path===i.path&&c.name===i.name);if(!a)throw new Error(`Could not find library for bytecode placeholder ${i.path}:${i.name}`);s=Kr(s,i.start,i.length,a.prepareDeploy(t,r).address)}return{bytecode:s,address:Jr({from:t,bytecode:s,salt:S})}}}function xo({config:e,forgeSourceDir:o,forgeOutDir:n}){let t=go(n).map(p=>{let g=H(qr.basename(p.path),p.name,n);return{path:p.path,name:p.name,abi:g.abi,prepareDeploy:_(g.bytecode,g.placeholders),deployedBytecodeSize:g.deployedBytecodeSize}}),r=z(e),s=k(o).map(({basename:p})=>p),i=Yr(e,s),c=H("System.sol","System",n).abi.filter(p=>p.type==="function").map(wo),d=Object.entries(i.systems).map(([p,g])=>{let h=g.namespace,w=g.name,y=bo({type:"system",namespace:h,name:w}),x=H(`${p}.sol`,p,n),T=x.abi.filter(m=>m.type==="function").map(wo).filter(m=>!c.includes(m)).map(m=>{let b=h===""?m:`${h}__${m}`;return{signature:b,selector:ho(b),systemId:y,systemFunctionSignature:m,systemFunctionSelector:ho(m)}});return{namespace:h,name:w,systemId:y,allowAll:g.openAccess,allowedAddresses:g.accessListAddresses,allowedSystemIds:g.accessListSystems.map(m=>bo({type:"system",namespace:h,name:i.systems[m].name})),prepareDeploy:_(x.bytecode,x.placeholders),deployedBytecodeSize:x.deployedBytecodeSize,abi:x.abi,functions:T}}),f=Gr(d,p=>p.systemId),u=Array.from(f.values()).filter(p=>p.length>1).flat();if(u.length){let p=u.map(g=>g.name);throw new Error(`Found systems with overlapping system ID: ${p.join(", ")}.
14
14
 
15
15
  System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}return{tables:r,systems:d,libraries:t}}import{getChainId as Tn}from"viem/actions";import{existsSync as Qr}from"fs";import Zr from"path";import Xr from"chalk";import{getScriptDirectory as en,forge as on}from"@latticexyz/common/foundry";async function So(e,o,n,t,r,s){let i=r?.replaceAll("\\","").split(" ")??[],a=Zr.join(await en(),e+".s.sol");if(!Qr(a)){console.log(`No script at ${a}, skipping post deploy hook`);return}console.log(Xr.blue(`Executing post deploy script at ${a}`)),await on(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",n,"-vvv",s?"--aws":"",...i],{profile:t})}import{kmsKeyToAccount as An}from"@latticexyz/common/kms";import To from"node:path";import{encodeField as dn}from"@latticexyz/protocol-parser/internal";import{bytesToHex as ln}from"viem";import{isHex as tn,size as rn}from"viem";import{z as O}from"zod";import{Abi as nn}from"abitype/zod";import{createRequire as sn}from"node:module";import{findUp as an}from"find-up";var Co=O.object({object:O.string().refine(tn),linkReferences:O.record(O.record(O.array(O.object({start:O.number(),length:O.number()}))))}),cn=O.object({bytecode:Co,deployedBytecode:Co,abi:nn});async function Do({packageJsonPath:e,artifactPath:o}){let n;try{let s=e??await an("package.json",{cwd:process.cwd()});if(!s)throw new Error("Could not find package.json to import relative to.");n=sn(s)(o)}catch(s){throw console.error(),console.error("Could not import contract artifact at",o),console.error(),s}let t=cn.parse(n),r=ie(t.bytecode.linkReferences);return{abi:t.abi,bytecode:t.bytecode.object,placeholders:r,deployedBytecodeSize:rn(t.deployedBytecode.object)}}var vo={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"};import{resolveWithContext as mn}from"@latticexyz/world/internal";async function de(e,o){return await Promise.all(e.modules.map(async t=>{let r=t.artifactPath;if(!r)if(t.name)r=vo[t.name]??To.join(o,`${t.name}.sol`,`${t.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(t.name)}`,"","with this:","",` artifactPath: ${JSON.stringify(r)}`,""].join(`
16
16
  `));else throw new Error("No `artifactPath` provided for module.");let s=To.basename(r,".json"),i=await Do({artifactPath:r}),a=t.args.map(c=>mn(c,{config:e})).map(c=>{let d=c.value instanceof Uint8Array?ln(c.value):c.value;return dn(c.type,d)});if(a.length>1)throw new Error(`${s} module should only have 0-1 args, but had ${a.length} args.`);return{name:s,installAsRoot:t.root,installData:a.length===0?"0x":a[0],prepareDeploy:_(i.bytecode,i.placeholders),deployedBytecodeSize:i.deployedBytecodeSize,abi:i.abi}}))}var P={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"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},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."}};async function E(e){let o=e.salt;if(o!=null&&!bn(o))throw new be("Expected hex string for salt");let n=e.profile??process.env.FOUNDRY_PROFILE,t=await xn(e.configPath),r=await wn(t),s=Sn(r);e.printConfig&&console.log($.green(`
@@ -36,4 +36,4 @@ Waiting for file changes\u2026
36
36
  `))}}),vs(Ts)).subscribe()}},zo=ks;import{getCreate2Address as No,sliceHex as Is,zeroHash as Os}from"viem";import{forge as Ps}from"@latticexyz/common/foundry";async function M(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 Ps(o,{cwd:e.cwd})}import Ws from"p-queue";import{MUDError as Bs}from"@latticexyz/common/errors";import{getStorageAt as Ms}from"viem/actions";import{execa as xe}from"execa";var js="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function Lo({client:e,rpc:o,systems:n,modules:t,worldAddress:r,deployerAddress:s,verifier:i,verifierUrl:a}){let c=s??await Q(e);if(!c)throw new Bs("No deployer address provided or found.");let d=await Ms(e,{address:r,slot:js}),f=d&&d!==Os,u=new Ws({concurrency:4});if(n.map(({name:p,bytecode:g})=>u.add(()=>M({name:p,rpc:o,verifier:i,verifierUrl:a,address:No({from:c,bytecode:g,salt:S})}).catch(h=>{console.error(`Error verifying system contract ${p}:`,h)}))),i==="sourcify")if(await xe("npm",["install"],{cwd:"node_modules/@latticexyz/store"}),await xe("npm",["install"],{cwd:"node_modules/@latticexyz/world"}),await xe("npm",["install"],{cwd:"node_modules/@latticexyz/world-modules"}),Object.entries(f?oe(c):ee(c)).map(([p,{bytecode:g}])=>u.add(()=>M({cwd:"node_modules/@latticexyz/world",name:p,rpc:o,verifier:i,verifierUrl:a,address:No({from:c,bytecode:g,salt:S})}).catch(h=>{console.error(`Error verifying world factory contract ${p}:`,h)}))),t.map(({name:p,prepareDeploy:g})=>{let{address:h}=g(c,[]);return u.add(()=>M({cwd:"node_modules/@latticexyz/world-modules",name:p,rpc:o,verifier:i,verifierUrl:a,address:h}).catch(w=>{console.error(`Error verifying module contract ${p}:`,w)}))}),f){let p=Is(d,-20);u.add(()=>M({cwd:"node_modules/@latticexyz/world",name:"WorldProxy",rpc:o,verifier:i,verifierUrl:a,address:r}).catch(g=>{console.error("Error verifying WorldProxy contract:",g)})),u.add(()=>M({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:i,verifierUrl:a,address:p}).catch(g=>{console.error("Error verifying World contract:",g)}))}else u.add(()=>M({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:i,verifierUrl:a,address:r}).catch(p=>{console.error("Error verifying World contract:",p)}));else console.log(""),console.log(`Note: MUD is currently unable to verify store, world, and world-modules contracts with ${i}. We are planning to expand support in a future version.`),console.log("")}import{loadConfig as Rs}from"@latticexyz/config/node";import{resolveWorldConfig as Hs}from"@latticexyz/world/internal";import{worldToV1 as $s}from"@latticexyz/world/config/v2";import{getOutDirectory as Es,getRpcUrl as Fs,getSrcDirectory as zs}from"@latticexyz/common/foundry";import{createWalletClient as Ns,http as Ls}from"viem";import Vo from"chalk";var Vs={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)"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},verifier:{type:"string",desc:"The verifier to use. Defaults to blockscout",default:"blockscout"},verifierUrl:{type:"string",desc:"The verification provider."}},Us={command:"verify",describe:"Verify contracts",builder(e){return e.options(Vs)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,n=await Rs(e.configPath),t=$s(n),r=e.srcDir??await zs(o),s=await Es(o),i=e.rpc??await Fs(o);console.log(Vo.bgBlue(Vo.whiteBright(`
37
37
  Verifying MUD contracts${o?" with profile "+o:""} to RPC ${i}
38
38
  `)));let a=Ns({transport:Ls(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),c=k(r).map(({basename:p})=>p),d=Hs(t,c),f=Object.keys(d.systems).map(p=>{let g=H(`${p}.sol`,p,s);return{name:p,bytecode:g.bytecode}}),u=await de(n,s);await Lo({client:a,rpc:i,systems:f,modules:u,deployerAddress:e.deployerAddress,worldAddress:e.worldAddress,verifier:e.verifier,verifierUrl:e.verifierUrl})}},Uo=Us;var ly=[Se,Ao,Ce,_s,De,ve,Po,Bo,Mo,Fo,zo,Ks,Uo];export{ly as commands};
39
- //# sourceMappingURL=commands-VSP7IDAM.js.map
39
+ //# sourceMappingURL=commands-D2G24ET6.js.map