Hi 游客

更多精彩,请登录!

比特池塘 区块链技术 正文
1、安装 Web3.py3 i! ^# A3 V" P; r

4 j: B0 d' c' f; T& H
  1. pip install web3.py
复制代码

% n) W3 d; F1 H6 U. H' j, ~
3 _* U# U2 d$ P( R7 F! Z2、注册 Infura 获得节点服务
5 R3 X" e" I; D( m使用邮箱注册 Infura 账户后,创建一个项目,即可获得以太坊节点服务,进入设置即可看到链接的URL
$ z/ [: g& k% T 04ab0f6855e74cb6b49a35b1f466da1f.png
4 w% n7 D; j" ^! v" O, I8 p- X% Z
可以选择主网测试网等,会有两个链接,一个是使用HTTPS的一个是使用WebSocket,按你的需求选择一个就行了,注意:Infura 个人免费请求次数,是每天有十万个请求。  H0 w/ U" Q" }+ ?4 X3 w7 {- z- H
4 f+ ]6 G% u$ I  P% F) o6 C$ e0 Q
3、代码示例
# A0 w3 n) q, I- S/ `& V
  1. 3 Z1 J) g" o; x8 w2 q& \
  2. from web3 import Web3, Y, L3 i, l9 [1 K
  3. import json  ~8 T: q6 `2 S/ j) U( M
  4. import time% a7 u; x6 @6 e; `
  5. import os) k3 _4 d$ w. C
  6. import logging% H) V' T  f0 m- g% w: e
  7. from django.conf import settings; R2 ?, K* B1 [
  8. from decimal import Decimal
    6 N1 M8 @/ S5 d# ]) T

  9. - |/ c% g' ^9 i7 @2 O& p9 d7 f- a
  10. . k# k  h. p1 R% a7 E
  11. class PayEthOrToken(object):
    . @9 k$ s/ V$ K. p. X
  12.     6 t3 m6 Q' U+ a; r2 f
  13.     def __init__(self):0 `/ D0 b: N0 Y
  14.         # 设置web3
    " Q+ a1 a9 \  C  }! R
  15.         self.web3 = Web3(Web3.HTTPProvider('your infura http url'))
    ' G; c8 p# U1 C1 m* {
  16.         # token合约地址
      J" Z4 q4 L  H: I/ N6 ?
  17.         self.contract_address = 'your contract address'; e% V5 s) a9 X8 t1 ~9 \) n
  18.         # 主钱包地址
    4 w( e! U4 \8 ?1 ~2 `; Y
  19.         self.wallet = 'your wallet address'  p- `# B8 O# ?. y  t; E# J
  20.         # 钱包的私钥
    * f  g- p9 L$ b7 W% [$ l, a
  21.         self.wallet_key = 'your wallet key') R, {+ d7 @- `% Y2 `
  22.         # 合约的abi test.json 是eth的abi json文件,可以在eth区块链浏览器上获得
    3 ~1 b) Y' \& K6 B6 _* m
  23.         with open('test.json', 'r') as f:
    ! u7 c! p: v  S, }
  24.             self.abi = json.loads(f.read())0 t8 }8 X& p# G! a
  25.         # 生成合约) V( t- B0 e. j( q/ _% U
  26.         self.contract = self.web3.eth.contract(address=self.contract_address, abi=self.abi)# m/ d; U0 z8 N. u6 ?
  27.         # 代币简写2 W2 q: S1 L' h( Y' m6 ]* J5 W
  28.         self.token_name = 'USDT'5 z9 l+ Q0 s8 ^+ v3 x0 g. X4 c
  29.         , r) w" Q: U" ]4 W6 S1 f
  30.     def transfer_usdt(self, to, value):( `7 Q, K7 _* a. _
  31.         '''进行代币转账" s5 X+ v) y" |+ J5 R& x3 X
  32.         args:
    7 a" x  w6 i- c% h/ c# Y
  33.             to str:接收代币的地址+ }1 M0 Y5 b4 d9 P0 T; {
  34.             value str/int:代币数量,以ether为单位,可以是字符串和int类型
    3 c6 B$ {: ?+ h! j
  35.         returns:6 h# r7 |4 {" g$ Q, x
  36.             (str, str):返回交易哈希,以及异常信息. ]5 E9 F# l9 O8 j
  37.         '''3 \: k" V4 ^) h% |; \
  38.         try:
    / m2 z' t4 r; ^* O& \+ B# T
  39.             token_balance = self.web3.fromWei(self.contract.functions.balanceOf(self.wallet).call(), 'ether')# c: t/ \2 a# p& p1 b1 C" W3 O
  40.             # 如果代币不足返回异常
    $ j: l  m: i8 q% U2 P+ k
  41.             if Decimal(token_balance) < Decimal(value):; S6 O' ^5 K- s* g5 J  h
  42.                 return None, 'Platform USDT token is insufficient, please try again later'
    " t$ m( k6 X9 T# E* b7 D1 t2 s* x
  43.             # 进行转账代币
    - A# t# P9 H) J- O2 V, h1 r
  44.             nonce = self.web3.eth.get_transaction_count(self.wallet): @; u) S+ O2 q! y+ A) B9 Y3 q; \. a
  45.             tx = {4 Y/ E6 b2 i! h1 D" S
  46.                 'from': self.wallet,0 n, u4 _2 h) Y* f7 a
  47.                 'nonce': nonce,
    8 M. r4 P  S" J! {) Z' R
  48.                 'gas': 100000,4 T! o* G! C4 F
  49.                 'gasPrice': self.web3.toWei('50', 'gwei'),) V: n( b3 i5 i- }! Z
  50.                 'chainId': 1
    * n* Z7 @7 Z! j& g$ r+ M& k
  51.             }
    9 A" T  s: y5 g4 y. v( q
  52.             to = Web3.toChecksumAddress(to)
    ' s. H( ?* R9 G! x* t) U
  53.             txn = self.contract.functions.transfer(to, self.web3.toWei(value, 'ether')).buildTransaction(tx)
    8 P4 G# X* |3 A4 C) U
  54.             signed_txn = self.web3.eth.account.sign_transaction(txn, private_key=self.wallet_key): I. P, e5 S! U' t$ N6 I" ~( w
  55.             tx_hash = self.web3.eth.send_raw_transaction(signed_txn.rawTransaction). \/ L, \9 n3 D8 |% g% _" P
  56.             return self.web3.toHex(tx_hash), 'pay success'! b2 V& G9 D  C. X0 f( ~
  57.         except Exception as e:
    ! `8 L. E5 \4 g. w
  58.             logging.error(f'转账{self.token_name}代币时发生异常:{e}')
    ) L$ a" }! c0 N; e0 B% _
  59.             logging.exception(e)+ N- J% O: R" i& U5 N$ d$ G
  60.             return None, str(e)# k. [% r4 \$ o  M% ]% S
  61.     " B+ r# e4 A# l
  62.     def transfer_eth(self, to, value):
    " E- m4 X+ Q0 {* O, B* p* C# L" @
  63.         '''进行eth转账
    ; {: o4 D8 }* M, C" U
  64.         args:) m& R6 S! X/ q  S
  65.             to str:接收以太坊的地址
    0 ~! c- Q/ D0 b8 a+ d
  66.             value str/int:数量,以ether为单位,可以是字符串和int类型4 W+ B- c9 J  _: F
  67.         returns:
    9 ^& o+ k" f( M) X+ t
  68.             str:返回交易哈希$ y7 I  [& x6 z
  69.         '''; i0 `+ x) l1 ~
  70.         try:8 h0 J4 l# Z8 t5 c; n
  71.             token_balance = self.web3.fromWei(self.web3.eth.get_balance(self.wallet), 'ether')+ l2 U) y' g- q* |
  72.             # 如果代币不足返回异常
    ; ]: F4 q& ]5 s! @7 E
  73.             if Decimal(token_balance) < Decimal(value):
    & L0 j0 ^% V% a0 v/ i% y. j& L
  74.                 return None, 'Platform ETH token is insufficient, please try again later'
    ' J. o4 z% {9 E$ H( D/ Y3 k
  75.             # 获取 nonce,这个是交易计数
    & I$ L& Y- p* \4 s$ J
  76.             to = Web3.toChecksumAddress(to)& G* S; X1 B& w- N, J: f+ x
  77.             nonce = self.web3.eth.get_transaction_count(self.wallet)2 V+ G! ]0 E1 ?+ R2 S3 z5 O0 X
  78.             tx = {7 ^( M6 H& t7 U7 ^" [$ e
  79.                 'nonce': nonce,1 b* Z, l0 z2 O: W- W# G
  80.                 'to': to,' d/ }$ n( [3 o5 q  f5 k) g6 ~
  81.                 'gas': 100000,
    9 W2 G3 G2 L. Q3 O
  82.                 'gasPrice': self.web3.toWei('50', 'gwei'),
    $ F( O# i  ]" b9 B, W
  83.                 'value': self.web3.toWei(value, 'ether'),
    ( [; Y! k: t4 ~$ l% L% w4 z, H( a
  84.                 'chainId': 1: b& G/ ?5 ~6 r% o: O- @
  85.             }
    $ a' }7 [7 m$ P' ]- Z4 P  g4 b" R$ y9 w
  86.             # 签名交易. b& w3 Q/ n! z# ^  t
  87.             signed_tx = self.web3.eth.account.sign_transaction(tx, self.wallet_key)& W6 P2 n  d/ l& ^
  88.             tx_hash = self.web3.eth.send_raw_transaction(signed_tx.rawTransaction)
    2 `9 @4 x0 ]" ~: f9 e+ E. G2 s2 l* ?9 W
  89.             return self.web3.toHex(tx_hash), 'pay success'$ \) L5 Q( N1 a6 f+ r& r9 n$ V
  90.         except Exception as e:
    , a1 W+ K  ^" T! @) d% _/ W
  91.             logging.error(f'转账eth时发生异常:{e}')
    9 f# a: V! d4 X! ~- T. R
  92.             logging.exception(e); q# G( Q; L: G
  93.             return None, str(e)1 e2 P8 T/ Y! W" v+ ~
复制代码

$ x+ {6 B/ a# g) [1 A+ A; l
标签: Python 代币转账
BitMere.com 比特池塘系信息发布平台,比特池塘仅提供信息存储空间服务。
声明:该文观点仅代表作者本人,本文不代表比特池塘立场,且不构成建议,请谨慎对待。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

成为第一个吐槽的人

常德小学生 初中生
  • 粉丝

    0

  • 关注

    0

  • 主题

    13