Contract.mjs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import {ethers} from "ethers";
  2. // 配置 provider,明确指定 chainId 并禁用 ENS
  3. const provider = new ethers.JsonRpcProvider("https://testnet.dplabs-internal.com");
  4. const privateKey = "0x4b833cf91c19c4d9434ffed4b18714ef032d2acf44caec110a1c2c7db151eb65";
  5. const wallet = new ethers.Wallet(privateKey, provider);
  6. const contractAddress = "0x76aaada469d23216be5f7c596fa25f282ff9b364";
  7. const contractABI = [
  8. "function deposit() public"
  9. ];
  10. async function validateSetup() {
  11. try {
  12. // 验证钱包地址
  13. if (!ethers.isAddress(wallet.address)) {
  14. throw new Error("Invalid wallet address derived from private key");
  15. }
  16. console.log("Wallet address:", wallet.address);
  17. // 检查账户余额
  18. const balance = await provider.getBalance(wallet.address);
  19. console.log("Wallet balance:", ethers.formatEther(balance), "PHRS");
  20. if (balance === 0n) {
  21. throw new Error("Wallet has no balance to pay for gas");
  22. }
  23. // 验证合约地址
  24. if (!ethers.isAddress(contractAddress)) {
  25. throw new Error("Invalid contract address");
  26. }
  27. // 检查合约是否部署
  28. const code = await provider.getCode(contractAddress);
  29. if (code === "0x") {
  30. throw new Error("No contract deployed at the specified address");
  31. }
  32. console.log("Contract is deployed at:", contractAddress);
  33. // 检查网络连接
  34. const network = await provider.getNetwork();
  35. console.log("Connected to network:", network);
  36. } catch (error) {
  37. console.error("Validation failed:", error.message);
  38. process.exit(1);
  39. }
  40. }
  41. // 发送交易
  42. async function deposit() {
  43. try {
  44. // 验证设置
  45. await validateSetup();
  46. // 初始化合约
  47. const contract = new ethers.Contract(contractAddress, contractABI, wallet);
  48. // 获取交易参数
  49. const nonce = await provider.getTransactionCount(wallet.address, "pending");
  50. const gasPrice = (await provider.getFeeData()).gasPrice;
  51. // 发送交易
  52. const tx = await contract.deposit({
  53. nonce,
  54. gasPrice,
  55. gasLimit: 100000 // 根据合约需求调整
  56. });
  57. console.log("Transaction sent:", tx.hash);
  58. // 等待交易确认
  59. const receipt = await tx.wait();
  60. console.log("Transaction confirmed in block:", receipt.blockNumber);
  61. } catch (error) {
  62. console.error("Error sending transaction:", error);
  63. process.exit(1);
  64. }
  65. }
  66. // 执行 deposit 函数
  67. deposit();