如何使用ethers.js在后端获取智能合约部署者地址
获取合约部署者地址的后端实现方法
方法1:使用Ethers.js(后端环境)
通过Ethers.js连接区块链节点,直接查询合约的创建交易信息,从中提取部署者地址:
const { ethers } = require("ethers"); async function getContractDeployer(contractAddress, rpcUrl) { const provider = new ethers.providers.JsonRpcProvider(rpcUrl); // 验证目标地址为合约地址 const contractCode = await provider.getCode(contractAddress); if (contractCode === "0x") { throw new Error("该地址不是合约地址"); } // 获取合约创建交易,从中提取部署者地址 const creationTx = await provider.getTransaction(contractAddress); return creationTx.from; } // 调用示例 const targetContractAddr = "0xYourTargetContractAddress"; const nodeRpcUrl = "https://your-node-rpc-url"; getContractDeployer(targetContractAddr, nodeRpcUrl) .then(deployer => console.log("部署者地址:", deployer)) .catch(err => console.error(err));
补充:工厂合约部署场景的处理
如果你的合约是通过工厂合约批量部署的,上述方法返回的是工厂合约地址。要获取实际发起部署的用户地址,需要依赖工厂合约的事件:
- 确保工厂合约部署新合约时触发包含部署者信息的事件,例如:
event ContractDeployed(address indexed deployer, address indexed newContract);
- 后端通过查询该事件获取实际部署者:
async function getFactoryDeployedContractDeployer(contractAddress, factoryAddress, rpcUrl) { const provider = new ethers.providers.JsonRpcProvider(rpcUrl); // 仅需工厂合约中对应事件的ABI片段 const factoryAbi = [ "event ContractDeployed(address indexed deployer, address indexed newContract)" ]; const factoryContract = new ethers.Contract(factoryAddress, factoryAbi, provider); // 查询目标合约对应的部署事件 const events = await factoryContract.queryFilter( factoryContract.filters.ContractDeployed(null, contractAddress), 0, "latest" ); if (events.length === 0) { throw new Error("未找到该合约的部署事件记录"); } return events[0].args.deployer; }
方法2:使用Web3.js
通过Web3.js实现相同逻辑,代码示例:
const Web3 = require("web3"); async function getContractDeployer(contractAddress, rpcUrl) { const web3 = new Web3(rpcUrl); // 验证合约地址有效性 const code = await web3.eth.getCode(contractAddress); if (code === "0x") { throw new Error("该地址不是合约地址"); } // 获取创建交易并返回部署者 const creationTx = await web3.eth.getTransaction(contractAddress); return creationTx.from; } // 调用示例 getContractDeployer("0xYourTargetContractAddress", "https://your-node-rpc-url") .then(deployer => console.log("部署者地址:", deployer)) .catch(err => console.error(err));
方法3:直接调用RPC接口(curl示例)
无需SDK,直接通过HTTP请求调用节点RPC接口:
# 1. 验证目标地址为合约地址 curl -X POST \ -H "Content-Type: application/json" \ --data '{"jsonrpc":"2.0","method":"eth_getCode","params":["0xYourTargetContractAddress", "latest"],"id":1}' \ https://your-node-rpc-url # 2. 假设已知合约创建区块号为0x1E240,查询该区块内的所有交易,找到to为null且contractAddress匹配的交易,其from即为部署者 curl -X POST \ -H "Content-Type: application/json" \ --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x1E240", true],"id":1}' \ https://your-node-rpc-url
注意事项
- 确保连接的RPC节点为全节点或归档节点,支持查询历史交易数据
- 克隆合约(如EIP-1167)的场景与工厂合约一致,需依赖克隆工厂的事件获取实际部署者
内容的提问来源于stack exchange,提问作者jiru chen
相关产品推荐
相关产品推荐

