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