使用Web3JS的API在页面中进行转账交易-案例

注意:代码需要在服务端运行!!!切勿双击html文件运行,点击下载源文件

web3.eth.sendTransaction

web3.eth.sendTransaction(transactionObject [, callback])

参数:
    Object - 要发送的交易对象。
      from: String - 指定的发送者的地址。如果不指定,使用web3.eth.defaultAccountto: String - (可选)交易消息的目标地址,如果是合约创建,则不填.
      value: Number|String|BigNumber - (可选)交易携带的货币量,以wei为单位。如果合约创建交易,则为初始的基金。
      gas: Number|String|BigNumber - (可选)默认是自动,交易可使用的gas,未使用的gas会退回。
      gasPrice: Number|String|BigNumber - (可选)默认是自动确定,交易的gas价格,默认是网络gas价格的平均值 。
      data: String - (可选)或者包含相关数据的字节字符串,如果是合约创建,则是初始化要用到的代码。
      nonce: Number - (可选)整数,使用此值,可以允许你覆盖你自己的相同nonce的,正在pending中的交易11Function - 回调函数,用于支持异步的方式执行[async]。
返回值:
	String - 32字节的交易哈希串。用16进制表示

获取个人账户信息

async function getAccount() {
	// 请求用户授权 解决web3js无法直接唤起Meta Mask获取用户身份
	const enable = await ethereum.enable();
	console.log(enable,11)

	// 授权获取账户
	// let accounts = await ethereum.request({ method: 'eth_requestAccounts' });
	let accounts = await web3.eth.getAccounts();
	AccountValue = accounts[0];
	console.log(AccountValue,1);

	// 返回指定地址账户的余额
	let balance = await web3.eth.getBalance(AccountValue);
	BalanceValue = web3.utils.fromWei(balance, 'ether');
	console.log(balance,BalanceValue,2);
	showAccount.innerHTML = AccountValue;
	showBalance.innerHTML = `wei:${balance}, ether:${BalanceValue}`;
}

转账交易

async function toPay() {
	showCont();
	// 转账
	var r = confirm("确认转账吗?");
	if (r == true) {
		// const res = await web3.eth.sendTransaction({
		//     from:AccountValue,
		//     to:toAccountValue,
		//     value:toBalanceValue,
		// });
		// console.log(res);
		web3.eth.sendTransaction({
			from: AccountValue,
			to: toAccountValue,
			value: toBalanceValue,
		}, (err, address) => {
			if (!err) {
				console.log(address);
				alert("转账成功!");
			} else {
				console.log(err);
			}
		});
	}
	else {
		alert("您已经取消转账!");
	}

}

附源码

<div id="app">
	<h5>转账</h5>
	<button class="Web3Button">获取我信息</button>
	<h2>我账户: <span class="showAccount"></span></h2>
	<h2>&nbsp;&nbsp;&nbsp;额: <span class="showBalance"></span></h2>
	<hr>
	<p class="cont"></p>
	<hr>
	<input type="text" class="account" value="" placeholder="填写被转账的账户">
	<input type="text" class="balance" value="" placeholder="转账金额,单位ETH"><br>
	<button class="btnPay">确认转账</button>

	<script src="./node_modules/web3/dist/web3.min.js"></script>
</div>

操作流程 

const ethereumButton = document.querySelector('.Web3Button');
const showAccount = document.querySelector('.showAccount');
const showBalance = document.querySelector('.showBalance');

const cont = document.querySelector('.cont');

const toAccount = document.querySelector('.account');
const toBalance = document.querySelector('.balance');
const btnPay = document.querySelector('.btnPay');

// 我的账户余额,对方账户余额
let AccountValue, BalanceValue, toAccountValue, toBalanceValue;

// 页面显示转账内容
function showCont() {
	// 我的账户余额,对方账户余额
	// AccountValue,BalanceValue,toAccountValue,toBalanceValue
	cont.innerHTML = `我的账户:${AccountValue}-->对方账户:${toAccountValue},余额:${BalanceValue},转账金额:${web3.utils.fromWei(toBalanceValue, 'ether')}`;
}
// 获取内容
toAccount.onblur = () => {
	toAccountValue = toAccount.value;
	console.log(toAccount.value);
}
toBalance.onblur = () => {
	if (toBalance.value) {
		// eth转wei 转账 web3.utils.toWei('1', 'ether')
		toBalanceValue = web3.utils.toWei(toBalance.value, 'ether');
		showCont();
	}
	console.log(toBalance.value, toBalanceValue);
}

// Web3浏览器检测
if (typeof window.ethereum !== 'undefined') {
	console.log('MetaMask is installed!');
}

// 实例化
window.web3 = new Web3(ethereum);
var web3 = window.web3;

// 检测MetaMask
if (web3.currentProvider.isMetaMask == true) {
	console.log('metamask 可用');
} else {
	console.log('metamask 不可用');
}

// 获取账户信息
ethereumButton.addEventListener('click', () => {
	getAccount();
});

async function getAccount() {
	// 请求用户授权 解决web3js无法直接唤起Meta Mask获取用户身份
	const enable = await ethereum.enable();
	console.log(enable,11)

	// 授权获取账户
	// let accounts = await ethereum.request({ method: 'eth_requestAccounts' });
	let accounts = await web3.eth.getAccounts();
	AccountValue = accounts[0];
	console.log(AccountValue,1);

	// 返回指定地址账户的余额
	let balance = await web3.eth.getBalance(AccountValue);
	BalanceValue = web3.utils.fromWei(balance, 'ether');
	console.log(balance,BalanceValue,2);
	showAccount.innerHTML = AccountValue;
	showBalance.innerHTML = `wei:${balance}, ether:${BalanceValue}`;

	console.log(AccountValue, balance, BalanceValue);
}

// 转账
btnPay.addEventListener('click', () => {
	toPay();
});

async function toPay() {
	showCont();
	// 转账
	var r = confirm("确认转账吗?");
	if (r == true) {
		// const res = await web3.eth.sendTransaction({
		//     from:AccountValue,
		//     to:toAccountValue,
		//     value:toBalanceValue,
		// });
		// console.log(res);
		web3.eth.sendTransaction({
			from: AccountValue,
			to: toAccountValue,
			value: toBalanceValue,
		}, (err, address) => {
			if (!err) {
				console.log(address);
				alert("转账成功!");
			} else {
				console.log(err);
			}
		});
	}
	else {
		alert("您已经取消转账!");
	}

}

 

posted @   JackieDYH  阅读(122)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示