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