Skip to main content

Nodejs 端使用示例

V5 版本写法

钱包创建

function createWallet() {
const { address, privateKey, mnemonic } = Wallet.createRandom();
console.log({ address, privateKey, mnemonic });
}

直接转账 ETH

async function transfer() {
const privateKey = "";
const provider = new ethers.providers.JsonRpcProvider("");
const wallet = new Wallet(privateKey, provider);
const tx = await wallet.sendTransaction({
to: "", // receiver
value: utils.parseEther("0.1"), // 转 0.1 ETH
data: "", // 如果只是转ETH,不需要填写。对于以太铭文是填写在这里
});
await tx.wait(3); // 等待3个确认块
console.log({ txhash: tx.hash });
}

调用合约

async function callContract() {
const privateKey = "";
const contractAddress = "";
const abi = [{ stateMutability: "payable", type: "testFunc" }];
const provider = new ethers.providers.JsonRpcProvider("");
const wallet = new Wallet(privateKey, provider);
const contract = new Contract(contractAddress, abi, wallet);
const tx = await contract.testFunc({
value: utils.parseEther("0.1"), // 如果这个合约方法是一个payable的,需要支付0.1ETH才需要这个字段
});
await tx.wait();
console.log({ txhash: tx.hash });
}

另一种写法

async function callContract2() {
const privateKey = "";
const contractAddress = "";
const abi = [{ stateMutability: "payable", type: "testFunc" }];
const provider = new ethers.providers.JsonRpcProvider("");
const signer = new Wallet(privateKey, provider);
const contract = new Contract(contractAddress, abi);
contract.connect(signer);
const tx = await contract.testFunc({
value: utils.parseEther("0.1"), // 如果这个合约方法是一个payable的,需要支付0.1ETH才需要这个字段
});
await tx.wait();
console.log({ txhash: tx.hash });
}