@latticexyz/cli 2.0.13-main-7129a1605 → 2.0.13-main-bc947685c
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.
@@ -1,39 +1,39 @@
|
|
1
|
-
import{a as J}from"./chunk-QXUPZVZL.js";import
|
2
|
-
gracefully shutting down from SIGINT (Crtl-C)`),t.kill(),process.exit()}),await t}},Ce=
|
1
|
+
import{a as J}from"./chunk-QXUPZVZL.js";import Js from"@latticexyz/gas-report";import qs from"@latticexyz/abi-ts";import{loadConfig as Xo,resolveConfigPath as et}from"@latticexyz/config/node";import{getSrcDirectory as ot}from"@latticexyz/common/foundry";import Jo from"node:path";import{tablegen as qo}from"@latticexyz/store/codegen";import{worldgen as Yo}from"@latticexyz/world/node";import{forge as Go,getRemappings as Qo}from"@latticexyz/common/foundry";import{globSync as _o}from"glob";import{basename as Ko}from"path";function k(e){return _o(`${e}/**/*.sol`).sort().map(o=>({path:o,basename:Ko(o,".sol")}))}import{execa as Zo}from"execa";async function q({rootDir:e,config:o,srcDir:n,foundryProfile:t=process.env.FOUNDRY_PROFILE}){let r=Jo.join(n,o.codegen.outputDirectory),s=await Qo(t);await Promise.all([qo({rootDir:e,config:o,remappings:s}),Yo(o,k(n),r)]),await Go(["build"],{profile:t}),await Zo("mud",["abi-ts"],{stdio:"inherit"})}import tt from"node:path";var rt={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 et(e.configPath),n=await Xo(o),t=await ot();await q({rootDir:tt.dirname(o),config:n,srcDir:t,foundryProfile:e.profile}),process.exit(0)}},Se=rt;import{rmSync as nt}from"fs";import{homedir as st}from"os";import at from"path";import{execa as it}from"execa";var dt={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=st();nt(at.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let n=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${n.join(" ")}`);let t=it("anvil",n,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
|
2
|
+
gracefully shutting down from SIGINT (Crtl-C)`),t.kill(),process.exit()}),await t}},Ce=dt;var ct={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)}},De=ct;import{loadConfig as lt,resolveConfigPath as mt}from"@latticexyz/config/node";import{tablegen as pt}from"@latticexyz/store/codegen";import{getRemappings as ft}from"@latticexyz/common/foundry";import yt from"node:path";var ut={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 mt(e.configPath),n=await lt(o),t=await ft();await pt({rootDir:yt.dirname(o),config:n,remappings:t}),process.exit(0)}},ve=ut;import le from"node:path";import{existsSync as yn,mkdirSync as un,readFileSync as gn,writeFileSync as ge}from"node:fs";import{getBalance as St,sendRawTransaction as Ct,sendTransaction as Ae,waitForTransactionReceipt as ke}from"viem/actions";var A={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c",creationCode:"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"};import Te from"debug";var Y=Te("mud:cli"),bt=Te("mud:cli");Y.log=console.debug.bind(console);bt.log=console.error.bind(console);var l=Y.extend("deploy"),ht=Y.extend("deploy");l.log=console.debug.bind(console);ht.log=console.error.bind(console);import{sliceHex as wt}from"viem";import{getBytecode as xt}from"viem/actions";var G=`0x${A.address}`;async function Q(e){let o=await xt(e,{address:G});if(o)return l("found CREATE2 deployer at",G),o!==wt(`0x${A.creationCode}`,14)&&console.warn(`
|
3
3
|
\u26A0\uFE0F Bytecode for deployer at ${G} did not match the expected CREATE2 bytecode. You may have unexpected results.
|
4
|
-
`),G}var
|
4
|
+
`),G}var me=`0x${A.address}`;async function Pe(e){let o=await Q(e);if(o!==void 0)return o;let n=BigInt(A.gasLimit)*BigInt(A.gasPrice),t=await St(e,{address:`0x${A.signerAddress}`}),r=n-t;if(r>0){l("sending gas for CREATE2 deployer to signer at",A.signerAddress);let a=await Ae(e,{chain:e.chain??null,to:`0x${A.signerAddress}`,value:r}),d=await ke(e,{hash:a});if(d.status!=="success")throw console.error("failed to send gas to deployer signer",d),new Error("failed to send gas to deployer signer")}l("deploying CREATE2 deployer at",me);let s=await Ct(e,{serializedTransaction:`0x${A.transaction}`}).catch(a=>{if(String(a).includes("only replay-protected (EIP-155) transactions allowed over RPC"))return console.warn(`
|
5
5
|
\u26A0\uFE0F Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.
|
6
6
|
|
7
7
|
We recommend running your chain's node with \`--rpc.allow-unprotected-txs\` to enable determinstic deployments.
|
8
|
-
`),l("deploying CREATE2 deployer"),Ae(e,{chain:e.chain??null,data:`0x${A.creationCode}`});throw a}),i=await ke(e,{hash:s});if(!i.contractAddress)throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");return i.contractAddress!==
|
9
|
-
\u26A0\uFE0F CREATE2 deployer created at ${i.contractAddress} does not match the CREATE2 determinstic deployer we expected (${
|
8
|
+
`),l("deploying CREATE2 deployer"),Ae(e,{chain:e.chain??null,data:`0x${A.creationCode}`});throw a}),i=await ke(e,{hash:s});if(!i.contractAddress)throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");return i.contractAddress!==me&&console.warn(`
|
9
|
+
\u26A0\uFE0F CREATE2 deployer created at ${i.contractAddress} does not match the CREATE2 determinstic deployer we expected (${me})`),i.contractAddress}import{waitForTransactionReceipt as er}from"viem/actions";import{waitForTransactionReceipt as Et}from"viem/actions";import{concatHex as Bt,getCreate2Address as Mt}from"viem";import{getBytecode as jt}from"viem/actions";import{padHex as vt}from"viem";import Tt from"@latticexyz/store/mud.config";import At from"@latticexyz/world/mud.config";import kt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{resourceToHex as Dt}from"@latticexyz/common";import{resolveUserTypes as Ie}from"@latticexyz/store/internal";function z(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([n])=>[n,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([n,t])=>[`${e.namespace}_${n}`,{namespace:e.namespace,name:t.name,tableId:Dt({type:t.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:t.name}),keySchema:Ie(t.keySchema,o),valueSchema:Ie(t.valueSchema,o)}]))}import{helloStoreEvent as Pt}from"@latticexyz/store";import{helloWorldEvent as It}from"@latticexyz/world";import{storeToV1 as Ot}from"@latticexyz/store/config/v2";import{worldToV1 as Wt}from"@latticexyz/world/config/v2";var S=vt("0x",{size:32}),N=parseInt("6000",16),j=z(Ot(Tt)),D=z(Wt(At)),Z=[Pt,It],v=kt,Oe=["2.0.0","2.0.1","2.0.2"],We=["2.0.0","2.0.1","2.0.2"];import{sendTransaction as Rt}from"@latticexyz/common";import Ht from"p-retry";import{wait as $t}from"@latticexyz/common/utils";async function Be({client:e,deployerAddress:o,bytecode:n,deployedBytecodeSize:t,label:r="contract"}){if(n.includes("__$"))throw new Error(`Found unlinked public library in ${r} bytecode`);let s=Mt({from:o,salt:S,bytecode:n});return await jt(e,{address:s,blockTag:"pending"})?(l("found",r,"at",s),[]):(t>N?console.warn(`
|
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{globSync as _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(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().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 Ht(()=>Rt(e,{chain:e.chain??null,to:o,data:Bt([S,n])}),{retries:3,onFailedAttempt:async a=>{let d=a.attemptNumber*500;l(`failed to deploy ${r}, retrying in ${d}ms...`),await $t(d)}})])}import{uniqueBy as Ft}from"@latticexyz/common/utils";async function I({client:e,deployerAddress:o,contracts:n}){let t=Ft(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 Et(e,{hash:s})}return r}import Ee 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{getCreate2Address as Vt,encodeDeployData as Ut,size as _t}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 zt from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{getCreate2Address as L,encodeDeployData as Nt,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),d=Re.bytecode.object,c=L({from:e,bytecode:d,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=Nt({bytecode:$e.bytecode.object,abi:zt,args:[t,i,c,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:d,deployedBytecodeSize:a,label:"batch call system",address:c},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=_t(Ee.deployedBytecode.object),t=Ut({bytecode:Ee.bytecode.object,abi:Lt,args:[o.InitModule.address]}),r=Vt({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 Kt from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{getCreate2Address as Jt,encodeDeployData as qt,size as Yt}from"viem";function oe(e){let o=X(e),n=Yt(Fe.deployedBytecode.object),t=qt({bytecode:Fe.bytecode.object,abi:Kt,args:[o.InitModule.address]}),r=Jt({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 or from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as tr}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as Gt,decodeEventLog as Qt,hexToString as ze,parseAbi as Zt}from"viem";import{isDefined as Xt}from"@latticexyz/common/utils";function re(e){let o=e.map(i=>{try{return{...i,...Qt({strict:!0,abi:Zt(Z),topics:i.topics,data:i.data})}}catch(a){if(a instanceof Gt)return;throw a}}).filter(Xt),{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 tr(e,{chain:e.chain??null,address:r,abi:or,functionName:"deployWorld",args:[n]});l("waiting for world deploy");let i=await er(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 pe,writeContract as cr}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as lr,keySchemaToHex as mr,valueSchemaToHex as pr}from"@latticexyz/protocol-parser/internal";import{parseAbiItem as rr,decodeAbiParameters as Le,parseAbiParameters as Ve}from"viem";import{hexToResource as nr}from"@latticexyz/common";import{storeSetRecordEvent as sr}from"@latticexyz/store";import{getLogs as ar}from"viem/actions";import{decodeKey as ir,decodeValueArgs as dr,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 ar(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:rr(sr),args:{tableId:j.store_Tables.tableId}})).map(r=>{let{tableId:s}=ir(j.store_Tables.keySchema,r.args.keyTuple),{namespace:i,name:a}=nr(s),d=dr(j.store_Tables.valueSchema,r.args),c=Ue(d.keySchema),f=Ue(d.valueSchema),u=Le(Ve("string[]"),d.abiEncodedKeyNames)[0],p=Le(Ve("string[]"),d.abiEncodedFieldNames)[0],g=[...f.staticFields,...f.dynamicFields],h=Object.fromEntries(c.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 fr from"p-retry";import{wait as yr}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(pe).join(", "));let i=n.filter(a=>!r.includes(a.tableId));return i.length?(l("registering tables",i.map(pe).join(", ")),await Promise.all(i.map(a=>fr(()=>cr(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerTable",args:[a.tableId,lr(a.valueSchema),mr(a.keySchema),pr(a.valueSchema),Object.keys(a.keySchema),Object.keys(a.valueSchema)]}),{retries:3,onFailedAttempt:async d=>{let c=d.attemptNumber*500;l(`failed to register table ${pe(a)}, retrying in ${c}ms...`),await yr(c)}})))):[]}import{getAddress as W}from"viem";import{writeContract as fe,resourceToLabel as U}from"@latticexyz/common";import{parseAbiItem as ur,HttpRequestError as gr}from"viem";import{getLogs as br}from"viem/actions";import{storeSpliceStaticDataEvent as hr}from"@latticexyz/store";import wr from"p-retry";async function ne({client:e,worldDeploy:o}){l("looking up resource IDs for",o.address);let t=(await wr(()=>br(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:ur(hr),args:{tableId:j.store_ResourceIds.tableId}}),{retries:3,onFailedAttempt:async r=>{if(!(r instanceof gr&&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 Pr,resourceToLabel as Ir}from"@latticexyz/common";import{decodeValueArgs as xr,encodeKey as Sr}from"@latticexyz/protocol-parser/internal";import{readContract as Cr}from"viem/actions";async function R({client:e,worldDeploy:o,table:n,key:t}){let[r,s,i]=await Cr(e,{blockNumber:o.stateBlock,address:o.address,abi:v,functionName:"getRecord",args:[n.tableId,Sr(n.keySchema,t)]});return xr(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:d,systemId:c})=>({selector:a,signature:s[a],systemFunctionSelector:d,systemFunctionSignature:s[d],systemId:c}))}import{parseAbiItem as Dr,getAddress as vr}from"viem";import{storeSpliceStaticDataEvent as Tr}from"@latticexyz/store";import{getLogs as Ar}from"viem/actions";import{decodeKey as kr}from"@latticexyz/protocol-parser/internal";async function ae({client:e,worldDeploy:o}){l("looking up resource access for",o.address);let t=(await Ar(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Dr(Tr),args:{tableId:D.world_ResourceAccess.tableId}})).map(s=>kr(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:vr(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(Pr).filter(i=>i.type==="system");return l("looking up systems",s.map(Ir).join(", ")),await Promise.all(s.map(async i=>{let{system:a,publicAccess:d}=await R({client:e,worldDeploy:o,table:D.world_Systems,key:{systemId:i.resourceId}}),c=t.filter(f=>f.systemId===i.resourceId);return{address:a,namespace:i.namespace,name:i.name,systemId:i.resourceId,allowAll:d,allowedAddresses:r.filter(({resourceId:f})=>f===i.resourceId).map(({address:f})=>f),functions:c}}))}import{wait as ye}from"@latticexyz/common/utils";import ue 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 d=a.map(m=>m.systemId),c=r.filter(m=>!d.includes(m.systemId));if(!c.length)return[];let f=c.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=c.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:c.map(m=>({bytecode:m.prepareDeploy(o,n).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,label:`${U(m)} system`}))});let p=await Promise.all(c.map(m=>ue(()=>fe(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 ye(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=>ue(()=>fe(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 ye(C)}})),...y.map(m=>ue(()=>fe(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 ye(C)}}))]);return[...p,...T]}import{waitForTransactionReceipt as fo}from"viem/actions";import{getAddress as Or,parseAbi as Wr}from"viem";import{getBlockNumber as Br,getLogs as Mr}from"viem/actions";var eo=new Map;async function oo(e,o){let n=Or(o),t=eo.get(n);if(t!=null)return t;l("looking up world deploy for",n);let r=await Br(e),s=await Mr(e,{strict:!0,address:n,events:Wr(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 jr,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(d=>d.signature).join(", "));let a=s.filter(d=>d.systemId!==r[d.selector]?.systemId);a.length&&console.warn("found",a.length,"functions already registered but pointing at a different system ID:",a.map(d=>d.signature).join(", "))}return i.length?(l("registering functions:",i.map(a=>a.signature).join(", ")),Promise.all(i.map(a=>{let{namespace:d}=jr(a.systemId);return d===""?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 c=>{let f=c.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 c=>{let f=c.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await no(f)}})}))):[]}import{BaseError as Rr}from"viem";import{writeContract as ao}from"@latticexyz/common";import{isDefined as Hr,wait as $r}from"@latticexyz/common/utils";import Er 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=>Er(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 Rr&&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 $r(a)}})))).filter(Hr)):[]}import{getAddress as co}from"viem";import{hexToResource as lo,resourceToHex as mo,writeContract as Fr}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)),d=(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(d.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${d.join(", ")}`);let c=t.filter(u=>!s.has(u));return c.length>0&&l("registering namespaces",Array.from(c).join(", ")),Promise.all(c.map(u=>Fr(e,{chain:e.chain??null,address:o.address,abi:v,functionName:"registerNamespace",args:[mo({namespace:u,type:"namespace",name:""})]})))}import{resourceToLabel as zr}from"@latticexyz/common";import{randomBytes as Nr}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),d=s??await Pe(e);await te(e,d,i),await I({client:e,deployerAddress:d,contracts:[...o.libraries.map(y=>({bytecode:y.prepareDeploy(d,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${y.path}:${y.name} library`})),...o.systems.map(y=>({bytecode:y.prepareDeploy(d,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${zr(y)} system`})),...n.map(y=>({bytecode:y.prepareDeploy(d,o.libraries).bytecode,deployedBytecodeSize:y.deployedBytecodeSize,label:`${y.name} module`}))]});let c=r?await oo(e,r):await Ne(e,d,t??`0x${Nr(32).toString("hex")}`,i);if(!Oe.includes(c.storeVersion))throw new Error(`Unsupported Store version: ${c.storeVersion}`);if(!We.includes(c.worldVersion))throw new Error(`Unsupported World version: ${c.worldVersion}`);let f=await po({client:e,worldDeploy:c,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:c,tables:a}),p=await Xe({client:e,deployerAddress:d,libraries:o.libraries,worldDeploy:c,systems:o.systems}),g=await so({client:e,worldDeploy:c,functions:o.systems.flatMap(y=>y.functions)}),h=await io({client:e,deployerAddress:d,libraries:o.libraries,worldDeploy:c,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"),c}import{createWalletClient as bn,http as hn,isHex as wn}from"viem";import{privateKeyToAccount as xn}from"viem/accounts";import{loadConfig as Sn,resolveConfigPath as Cn}from"@latticexyz/config/node";import{worldToV1 as Dn}from"@latticexyz/world/config/v2";import{getOutDirectory as vn,getRpcUrl as Tn,getSrcDirectory as An}from"@latticexyz/common/foundry";import $ from"chalk";import{MUDError as be}from"@latticexyz/common/errors";import Gr from"path";import{resolveWorldConfig as Qr}from"@latticexyz/world/internal";import{resourceToHex as bo}from"@latticexyz/common";import{toFunctionSelector as ho,toFunctionSignature as wo}from"viem";import{readFileSync as Lr}from"fs";import Vr from"path";import{MUDError as de}from"@latticexyz/common/errors";import{size as Ur}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=Vr.join(n,e,o+".json");try{t=JSON.parse(Lr(r,"utf8"))}catch{throw new de(`Error reading file at ${r}`)}let s=t?.bytecode?.object;if(!s)throw new de(`No bytecode found in ${r}`);let i=t?.deployedBytecode?.object;if(!i)throw new de(`No deployed bytecode found in ${r}`);let a=t?.abi;if(!a)throw new de(`No ABI found in ${r}`);let d=ie(t?.bytecode?.linkReferences??{});return{abi:a,bytecode:s,placeholders:d,deployedBytecodeSize:Ur(i)}}import{groupBy as Zr}from"@latticexyz/common/utils";import{readFileSync as Kr}from"fs";import{globSync as Jr}from"glob";import _r from"toposort";function uo(e,o,n){let t=_r(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=Jr(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().map(t=>JSON.parse(Kr(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,d])=>Object.keys(d).map(c=>({path:a,name:c,dependentPath:r,dependentName:s})))});return uo(n,t=>`${t.path}:${t.name}`,t=>[`${t.dependentPath}:${t.dependentName}`])}import{spliceHex as qr}from"@latticexyz/common";import{getCreate2Address as Yr}from"viem";function _(e,o){return function(t,r){let s=e;for(let i of o){let a=r.find(d=>d.path===i.path&&d.name===i.name);if(!a)throw new Error(`Could not find library for bytecode placeholder ${i.path}:${i.name}`);s=qr(s,i.start,i.length,a.prepareDeploy(t,r).address)}return{bytecode:s,address:Yr({from:t,bytecode:s,salt:S})}}}function xo({config:e,forgeSourceDir:o,forgeOutDir:n}){let t=go(n).map(p=>{let g=H(Gr.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=Qr(e,s),d=H("System.sol","System",n).abi.filter(p=>p.type==="function").map(wo),c=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=>!d.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=Zr(c,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
|
-
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:
|
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(
|
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:c,libraries:t}}import{getChainId as kn}from"viem/actions";import{existsSync as Xr}from"fs";import en from"path";import on from"chalk";import{getScriptDirectory as tn,forge as rn}from"@latticexyz/common/foundry";async function So(e,o,n,t,r,s){let i=r?.replaceAll("\\","").split(" ")??[],a=en.join(await tn(),e+".s.sol");if(!Xr(a)){console.log(`No script at ${a}, skipping post deploy hook`);return}console.log(on.blue(`Executing post deploy script at ${a}`)),await rn(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",n,"-vvv",s?"--aws":"",...i],{profile:t})}import{kmsKeyToAccount as Pn}from"@latticexyz/common/kms";import To from"node:path";import{encodeField as mn}from"@latticexyz/protocol-parser/internal";import{bytesToHex as pn}from"viem";import{isHex as nn,size as sn}from"viem";import{z as O}from"zod";import{Abi as an}from"abitype/zod";import{createRequire as dn}from"node:module";import{findUp as cn}from"find-up";var Co=O.object({object:O.string().refine(nn),linkReferences:O.record(O.record(O.array(O.object({start:O.number(),length:O.number()}))))}),ln=O.object({bytecode:Co,deployedBytecode:Co,abi:an});async function Do({packageJsonPath:e,artifactPath:o}){let n;try{let s=e??await cn("package.json",{cwd:process.cwd()});if(!s)throw new Error("Could not find package.json to import relative to.");n=dn(s)(o)}catch(s){throw console.error(),console.error("Could not import contract artifact at",o),console.error(),s}let t=ln.parse(n),r=ie(t.bytecode.linkReferences);return{abi:t.abi,bytecode:t.bytecode.object,placeholders:r,deployedBytecodeSize:sn(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 fn}from"@latticexyz/world/internal";async function ce(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
|
+
`));else throw new Error("No `artifactPath` provided for module.");let s=To.basename(r,".json"),i=await Do({artifactPath:r}),a=t.args.map(d=>fn(d,{config:e})).map(d=>{let c=d.value instanceof Uint8Array?pn(d.value):d.value;return mn(d.type,c)});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&&!wn(o))throw new be("Expected hex string for salt");let n=e.profile??process.env.FOUNDRY_PROFILE,t=await Cn(e.configPath),r=await Sn(t),s=Dn(r);e.printConfig&&console.log($.green(`
|
17
17
|
Resolved config:
|
18
|
-
`),JSON.stringify(s,null,2));let i=e.srcDir??await
|
19
|
-
Deploying MUD contracts${n?" with profile "+n:""} to RPC ${
|
20
|
-
`))),e.skipBuild||await q({
|
18
|
+
`),JSON.stringify(s,null,2));let i=e.srcDir??await An(n),a=await vn(n),d=e.rpc??await Tn(n);console.log($.bgBlue($.whiteBright(`
|
19
|
+
Deploying MUD contracts${n?" with profile "+n:""} to RPC ${d}
|
20
|
+
`))),e.skipBuild||await q({rootDir:le.dirname(t),config:r,srcDir:i,foundryProfile:n});let c=xo({config:s,forgeSourceDir:i,forgeOutDir:a}),f=await ce(r,a),u=await(async()=>{if(e.kms){let y=process.env.AWS_KMS_KEY_ID;if(!y)throw new be("Missing `AWS_KMS_KEY_ID` environment variable. This is required when using with `--kms` option.");return await Pn({keyId:y})}else{let y=process.env.PRIVATE_KEY;if(!y)throw new be(`Missing PRIVATE_KEY environment variable.
|
21
21
|
Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
|
22
|
-
in your contracts directory to use the default anvil private key.`);return
|
22
|
+
in your contracts directory to use the default anvil private key.`);return xn(y)}})(),p=bn({transport:hn(d,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:u});console.log("Deploying from",p.account.address);let g=Date.now(),h=await yo({deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,client:p,config:c,modules:f,withWorldProxy:r.deploy.upgradeableWorldImplementation});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await So(s.postDeployScript,h.address,d,n,e.forgeScriptOptions,!!e.kms),console.log($.green("Deployment completed in",(Date.now()-g)/1e3,"seconds"));let w={worldAddress:h.address,blockNumber:Number(h.deployBlock)};if(e.saveDeployment){let y=await kn(p),x=le.join(s.deploysDirectory,y.toString());un(x,{recursive:!0}),ge(le.join(x,"latest.json"),JSON.stringify(w,null,2)),ge(le.join(x,Date.now()+".json"),JSON.stringify(w,null,2));let T=[1337,31337],m=yn(s.worldsFile)?JSON.parse(gn(s.worldsFile,"utf-8")):{};m[y]={address:w.worldAddress,blockNumber:T.includes(y)?void 0:w.blockNumber},ge(s.worldsFile,JSON.stringify(m,null,2)),console.log($.bgGreen($.whiteBright(`
|
23
23
|
Deployment result (written to ${s.worldsFile} and ${x}):
|
24
|
-
`)))}return console.log(w),h}var
|
24
|
+
`)))}return console.log(w),h}var In={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(P)},async handler(e){try{await E(e)}catch(o){J(o),process.exit(1)}process.exit(0)}},Ao=In;import{loadConfig as On}from"@latticexyz/config/node";import{worldgen as Wn}from"@latticexyz/world/node";import{getSrcDirectory as Bn}from"@latticexyz/common/foundry";import ko from"path";import{rmSync as Mn}from"fs";var jn={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 Rn(e),process.exit(0)}};async function Rn(e){let o=e.srcDir??await Bn(),n=k(o),t=e.config??await On(e.configPath),r=ko.join(o,t.codegen.outputDirectory);e.clean&&Mn(ko.join(r,t.codegen.worldgenDirectory),{recursive:!0,force:!0}),await Wn(t,n,r)}var Po=jn;import K from"chalk";import{readFileSync as zn,writeFileSync as Nn}from"fs";import we from"path";import{MUDError as F}from"@latticexyz/common/errors";var Io={name:"@latticexyz/cli",version:"2.0.12",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:"./dist/mud.js"},files:["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":"rimraf dist","clean:test-tables":"rimraf src/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",prepare:"mkdir -p ./dist && touch ./dist/mud.js",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@aws-sdk/client-kms":"^3.556.0","@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@latticexyz/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*",abitype:"1.0.0","asn1.js":"^5.4.1",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",ethers:"^5.7.2",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",typescript:"5.4.2",viem:"2.9.20",yargs:"^17.7.1",zod:"^3.22.2","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/node":"^18.15.11","@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",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.34.6"}};import{globSync as Ln}from"glob";import{ZodError as $n,z as Oo}from"zod";var En=Oo.object({MUD_PACKAGES:Oo.string().transform(e=>JSON.parse(e))});function Fn(){try{return En.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/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/query":{"localPath":"packages/query"},"@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/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof $n){let{...o}=e.format();console.error(`
|
25
25
|
Missing or invalid environment variables:
|
26
26
|
|
27
27
|
${Object.keys(o).join(`
|
28
28
|
`)}
|
29
|
-
`),process.exit(1)}throw e}}var he
|
30
|
-
`),console.log(`Updating ${e}`),Wo(i,r.dependencies),Wo(a,r.devDependencies),r;function c
|
29
|
+
`),process.exit(1)}throw e}}var he=Fn().MUD_PACKAGES;var Vn={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"],n=o.reduce((r,s)=>e[s]?r+1:r,0);if(n===0)throw new F(`You need to provide one these options: ${o.join(", ")}`);if(n>1)throw new F(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await Un(e));let t=Ln("**/package.json").sort().filter(r=>!r.includes("node_modules"));for(let r of t)_n(r,e)}catch(o){J(o)}finally{process.exit(0)}}};async function Un(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(K.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${Io.name}`)).json()}catch{throw new F("Could not fetch available MUD versions")}if(e.tag){let n=o["dist-tags"][e.tag];if(!n)throw new F(`Could not find npm version with tag "${e.tag}"`);return console.log(K.green(`Latest version with tag ${e.tag}: ${n}`)),n}if(e.commit){let n=e.commit.substring(0,8),t=Object.keys(o.versions).find(r=>r.includes(n));if(!t)throw new F(`Could not find npm version based on commit "${e.commit}"`);return console.log(K.green(`Version from commit ${e.commit}: ${t}`)),t}return e.mudVersion}function _n(e,o){let{link:n}=o,{mudVersion:t}=o,r=Kn(e),s=Object.keys(he),i={};for(let c in r.dependencies)s.includes(c)&&(i[c]=r.dependencies[c]);let a={};for(let c in r.devDependencies)s.includes(c)&&(a[c]=r.devDependencies[c]);for(let c in r.dependencies)s.includes(c)&&(r.dependencies[c]=d(c,"dependencies"));for(let c in r.devDependencies)s.includes(c)&&(r.devDependencies[c]=d(c,"devDependencies"));return Nn(e,JSON.stringify(r,null,2)+`
|
30
|
+
`),console.log(`Updating ${e}`),Wo(i,r.dependencies),Wo(a,r.devDependencies),r;function d(c,f){return n&&(t=Jn(e,n,c)),t||r[f][c]}}function Kn(e){try{let o=zn(e,"utf8");return JSON.parse(o)}catch{throw new F("Could not read JSON at "+e)}}function Wo(e,o){for(let n in e)e[n]!==o[n]&&console.log(`${n}: ${K.red(e[n])} -> ${K.green(o[n])}`)}function Jn(e,o,n){let t=we.relative(we.dirname(e),process.cwd());return"link:"+we.join(t,o,he[n].localPath)}var Bo=Vn;import{anvil as qn,forge as Yn,getRpcUrl as Gn}from"@latticexyz/common/foundry";import Qn from"chalk";var Zn={...P,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"}},Xn={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Zn)},async handler(e){if(!e.worldAddress){let r=["--block-base-fee-per-gas","0","--port",String(e.port)];qn(r)}let o=e.worldAddress?await Gn(e.profile):`http://127.0.0.1:${e.port}`,n=e.worldAddress??(await E({...e,saveDeployment:!1,rpc:o})).address;console.log(Qn.blue("World address",n));let t=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Yn(["test","--fork-url",o,...t],{profile:e.profile,env:{WORLD_ADDRESS:n}}),process.exit(0)}catch(r){console.error(r),process.exit(1)}}},Mo=Xn;import{existsSync as es,readFileSync as os}from"fs";import{ethers as jo}from"ethers";import{loadConfig as ts}from"@latticexyz/config/node";import{MUDError as Ro}from"@latticexyz/common/errors";import{cast as rs,getRpcUrl as ns,getSrcDirectory as ss}from"@latticexyz/common/foundry";import{resolveWorldConfig as as}from"@latticexyz/world/internal";import is from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import Ho from"@latticexyz/world/mud.config";import{resourceToHex as Eo}from"@latticexyz/common";import{createClient as ds,http as cs}from"viem";import{getChainId as ls}from"viem/actions";import{worldToV1 as ms}from"@latticexyz/world/config/v2";var $o=Eo({type:"system",namespace:Ho.namespace,name:Ho.tables.world__Systems.name}),ps={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"},srcDir:{type:"string",description:"Source directory. Defaults to foundry src directory."},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){e.profile??=process.env.FOUNDRY_PROFILE;let{profile:o}=e;e.srcDir??=await ss(o),e.rpc??=await ns(o);let{tx:n,configPath:t,srcDir:r,rpc:s}=e,i=k(r),a=await ts(t),d=ms(a),c=as(d,i.map(({basename:T})=>T)),f=e.worldAddress??await fs(d.worldsFile,s),u=new jo.providers.StaticJsonRpcProvider(s),p=new jo.Contract(f,is,u),g=d.namespace,h=Object.values(c.systems).map(({name:T})=>T),w=await p.getFieldLayout($o),y=[];for(let T of h){let m=Eo({type:"system",namespace:g,name:T}),b=await p.getField($o,[m],0,w);y.push({name:T,address:b})}let x=await rs(["run","--label",`${f}:World`,...y.map(({name:T,address:m})=>["--label",`${m}:${T}`]).flat(),`${n}`]);console.log(x),process.exit(0)}},Fo=ps;async function fs(e,o){if(es(e)){let n=ds({transport:cs(o)}),t=await ls(n),r=JSON.parse(os(e,"utf-8"));if(!r[t])throw new Ro(`chainId ${t} is missing in worldsFile "${e}"`);return r[t].address}else throw new Ro("worldAddress is not specified and worldsFile is missing")}import{anvil as ys,getScriptDirectory as us,getSrcDirectory as gs}from"@latticexyz/common/foundry";import B from"chalk";import bs from"chokidar";import{loadConfig as hs,resolveConfigPath as ws}from"@latticexyz/config/node";import xs from"path";import{homedir as Ss}from"os";import{rmSync as Cs}from"fs";import{BehaviorSubject as Ds,debounceTime as vs,exhaustMap as Ts,filter as As}from"rxjs";import{isDefined as ks}from"@latticexyz/common/utils";var Ps={rpc:P.rpc,configPath:P.configPath,alwaysRunPostDeploy:P.alwaysRunPostDeploy,forgeScriptOptions:P.forgeScriptOptions,worldAddress:P.worldAddress},Is={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(Ps)},async handler(e){let o=e.rpc,n=e.configPath??await ws(e.configPath),t=await gs(),r=await us(),s=await hs(n);if(!e.rpc){console.log(B.gray("Cleaning devnode cache"));let c=Ss();Cs(xs.join(c,".foundry","anvil","tmp"),{recursive:!0,force:!0}),ys(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let i=new Ds(Date.now());bs.watch([n,t,r],{ignoreInitial:!0}).on("all",async(c,f)=>{f.includes(n)&&(console.log(B.blue("Config changed, queuing deploy\u2026")),i.next(Date.now())),(f.includes(t)||f.includes(r))&&(f.includes(s.codegen.outputDirectory)||(console.log(B.blue("Contracts changed, queuing deploy\u2026")),i.next(Date.now())))});let a=e.worldAddress;i.pipe(vs(200),Ts(async c=>{a&&console.log(B.blue("Rebuilding and upgrading world\u2026"));try{let f=await E({...e,configPath:n,rpc:o,rpcBatch:!1,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,deployerAddress:void 0,worldAddress:a,srcDir:t,salt:"0x",kms:void 0});return a=f.address,c<i.value?i.next(i.value):console.log(B.gray(`
|
31
31
|
Waiting for file changes\u2026
|
32
32
|
`)),f}catch(f){console.error(B.bgRed(B.whiteBright(`
|
33
33
|
Error while attempting deploy
|
34
34
|
`))),console.error(f),console.log(B.gray(`
|
35
35
|
Waiting for file changes\u2026
|
36
|
-
`))}}),
|
36
|
+
`))}}),As(ks)).subscribe()}},zo=Is;import{getCreate2Address as No,sliceHex as Ws,zeroHash as Bs}from"viem";import{forge as Os}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 Os(o,{cwd:e.cwd})}import Ms from"p-queue";import{MUDError as js}from"@latticexyz/common/errors";import{getStorageAt as Rs}from"viem/actions";import{execa as xe}from"execa";var Hs="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function Lo({client:e,rpc:o,systems:n,modules:t,worldAddress:r,deployerAddress:s,verifier:i,verifierUrl:a}){let d=s??await Q(e);if(!d)throw new js("No deployer address provided or found.");let c=await Rs(e,{address:r,slot:Hs}),f=c&&c!==Bs,u=new Ms({concurrency:4});if(n.map(({name:p,bytecode:g})=>u.add(()=>M({name:p,rpc:o,verifier:i,verifierUrl:a,address:No({from:d,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(d):ee(d)).map(([p,{bytecode:g}])=>u.add(()=>M({cwd:"node_modules/@latticexyz/world",name:p,rpc:o,verifier:i,verifierUrl:a,address:No({from:d,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(d,[]);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=Ws(c,-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 $s}from"@latticexyz/config/node";import{resolveWorldConfig as Es}from"@latticexyz/world/internal";import{worldToV1 as Fs}from"@latticexyz/world/config/v2";import{getOutDirectory as zs,getRpcUrl as Ns,getSrcDirectory as Ls}from"@latticexyz/common/foundry";import{createWalletClient as Vs,http as Us}from"viem";import Vo from"chalk";var _s={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."}},Ks={command:"verify",describe:"Verify contracts",builder(e){return e.options(_s)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,n=await $s(e.configPath),t=Fs(n),r=e.srcDir??await Ls(o),s=await zs(o),i=e.rpc??await Ns(o);console.log(Vo.bgBlue(Vo.whiteBright(`
|
37
37
|
Verifying MUD contracts${o?" with profile "+o:""} to RPC ${i}
|
38
|
-
`)));let a=
|
39
|
-
//# sourceMappingURL=commands-
|
38
|
+
`)));let a=Vs({transport:Us(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),d=k(r).map(({basename:p})=>p),c=Es(t,d),f=Object.keys(c.systems).map(p=>{let g=H(`${p}.sol`,p,s);return{name:p,bytecode:g.bytecode}}),u=await ce(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=Ks;var yy=[Se,Ao,Ce,Js,De,ve,Po,Bo,Mo,Fo,zo,qs,Uo];export{yy as commands};
|
39
|
+
//# sourceMappingURL=commands-4H2PRTRK.js.map
|