3

solidity | 通过合约进行转账

 1 year ago
source link: https://benpaodewoniu.github.io/2022/06/21/solidity41/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

这里是通过合约进行转账。

主要步骤如下:

  • bsc testnet 中创建一个 ERC20 的代币
  • 创建一个可以转移币的合约
  • 将上述的 ERC20 代币转移到合约中
  • 通过 python 转移合约中的代币

在 bsc testnet 中创建一个 ERC20 的代币

这个步骤不做任何解释了,网上已经有很多开源的代码了。

创建一个可以转移币的合约

合约的内容如下。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

// 合约调用 pancakeswap
// 合约转出任意代币

interface functionContract {
function transfer(address recipient, uint256 amount) external returns (bool);

function approve(address spender, uint256 amount) external returns (bool);
}


contract MultiTrade {

constructor() {
}

function tokenTransfer(address tokenaddress, address toaddress, uint tokenAmount) public {
functionContract token = functionContract(tokenaddress);
token.transfer(toaddress, tokenAmount);
}
}

部署到 bsc testnet 之后,合约地址如下

将上述的 ERC20 代币转移到合约中

转移的 tx 如下

通过 python 转移合约中的代币

from web3 import Web3

from Constant.Strategy.StrategyConstant import StrategyType

abi = """[{"inputs":[{"internalType":"address","name":"tokenaddress","type":"address"},{"internalType":"address","name":"toaddress","type":"address"},{"internalType":"uint256","name":"tokenAmount","type":"uint256"}],"name":"tokenTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"stateMutability":"nonpayable","type":"constructor"}]"""


class Multiswap:
name = StrategyType.MULTISWAP.value

def __init__(self, strategyEngine):
self.web3 = Web3(Web3.HTTPProvider('https://data-seed-prebsc-1-s1.binance.org:8545/'))
self.strategyEngine = strategyEngine
# 0x1EF43774AbE961a1F3fDc547dfDD205fE766c091 部署合约的地址
self.multiswap = self.web3.eth.contract(
address=Web3.toChecksumAddress("0x1EF43774AbE961a1F3fDc547dfDD205fE766c091"), abi=abi)

def hello_world(self):
# 0xD1B260aba3bA6f3D3099725b1b1C7cdD12581974 调用合约的地址
nonce = self.web3.eth.getTransactionCount("0xD1B260aba3bA6f3D3099725b1b1C7cdD12581974")
transaction = self.multiswap.functions.tokenTransfer(
# 0x521A72e54a88C49B36Ebce2A13Fa8e40184c6aD7 要转移的 ERC20 的合约地址
Web3.toChecksumAddress("0x521A72e54a88C49B36Ebce2A13Fa8e40184c6aD7"),
# 0x177C713E09cA2C5B703C05E40F3846dD77108f94 要转移的地址
Web3.toChecksumAddress("0x177C713E09cA2C5B703C05E40F3846dD77108f94"),
int(0.001 * (10 ** 18))
).buildTransaction({
'gas': 241838,
'gasPrice': self.web3.toWei('10', 'gwei'),
'nonce': nonce,
})
signed_tx = self.web3.eth.account.signTransaction(transaction,
"private")
txn_hash = self.web3.eth.sendRawTransaction(signed_tx.rawTransaction)
print('txn_hash:', Web3.toHex(txn_hash))


if __name__ == '__main__':
l = Multiswap(None)
l.hello_world()

转移的 tx 如下


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK