forked from coccoinomane/web3cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken_controller.py
More file actions
306 lines (290 loc) · 11.2 KB
/
Copy pathtoken_controller.py
File metadata and controls
306 lines (290 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import argparse
import decimal
from cement import ex
from playhouse.shortcuts import model_to_dict
from web3cli.exceptions import Web3CliError
from web3cli.framework.controller import Controller
from web3cli.helpers import args
from web3cli.helpers.client_factory import make_contract_client, make_contract_wallet
from web3cli.helpers.render import render, render_table
from web3cli.helpers.tx import send_contract_tx
from web3core.exceptions import ContractNotFound
from web3core.helpers.misc import yes_or_exit
from web3core.helpers.resolve import resolve_address
from web3core.models.contract import Contract
class TokenController(Controller):
"""Handler of the `w3 token` command"""
class Meta:
label = "token"
help = "interact with ERC20 tokens"
stacked_type = "nested"
stacked_on = "base"
@ex(
help="Approve the given spender to spend the given amount of tokens",
arguments=[
(["token"], {"help": "Token to approve"}),
(["spender"], {"help": "Address or name of the spender to be approved"}),
(
["amount"],
{
"help": "Amount of tokens to approve, in token units; leave empty to approve the maximum amount",
"type": float,
"nargs": "?",
},
),
(
["--check"],
{
"help": "Whether to stop if the spender already has enough allowance",
"action": argparse.BooleanOptionalAction,
"default": True,
},
),
(
["--wei"],
{
"help": "Use the smallest unit of the token instead of the token's unit",
"action": argparse.BooleanOptionalAction,
"default": False,
},
),
*args.tx_args(),
*args.chain_and_rpc(),
*args.signer_and_gas(),
args.force(),
],
)
def approve(self) -> None:
# Parse arguments
spender = resolve_address(self.app.pargs.spender, chain=self.app.chain.name)
# Initialize client
signer = make_contract_wallet(self.app, self.app.pargs.token)
# Compute amount in token units, and amount in wei
if not self.app.pargs.amount:
amount = None
amount_in_wei = 2**256 - 1
elif self.app.pargs.wei:
decimals = signer.functions["decimals"]().call()
amount_in_wei = int(self.app.pargs.amount)
amount = amount_in_wei / 10**decimals
else:
decimals = signer.functions["decimals"]().call()
amount = self.app.pargs.amount
amount_in_wei = int(amount * 10**decimals)
# Approve
if self.app.pargs.check:
self.app.log.debug("Checking token allowance...")
allowance = signer.functions["allowance"](
self.app.signer.address, spender
).call()
# If allowance is not sufficient, approve
if allowance >= amount_in_wei:
self.app.log.info(
f"Token allowance already sufficient {allowance} >= {amount_in_wei}"
)
return
# Confirm
if not self.app.pargs.force:
what = (
(
str(amount_in_wei if self.app.pargs.wei else amount)
if amount is not None
else "infinite"
)
+ " "
+ self.app.pargs.token
+ (" (wei)" if self.app.pargs.wei else "")
)
print(
f"You are about to approve {spender} on chain {self.app.chain.name} to spend {what} on behalf of {signer.user_address}"
)
yes_or_exit(logger=self.app.log.info)
self.app.log.debug("Approving spender to spend token...")
output = send_contract_tx(
self.app,
signer,
signer.functions["approve"](spender, amount_in_wei),
)
# Print output
render(self.app, output)
@ex(
help="Revoke spending permissions from the given spender",
arguments=[
(["token"], {"help": "Token to approve"}),
(["spender"], {"help": "Address or name of the spender to be revoked"}),
*args.tx_args(),
*args.chain_and_rpc(),
*args.signer_and_gas(),
args.force(),
],
)
def revoke(self) -> None:
spender = resolve_address(self.app.pargs.spender, chain=self.app.chain.name)
signer = make_contract_wallet(self.app, self.app.pargs.token)
# Confirm
if not self.app.pargs.force:
print(
f"Revoke permissions to {spender} on chain {self.app.chain.name} to spend on behalf of {signer.user_address}?"
)
yes_or_exit(logger=self.app.log.info)
self.app.log.debug("Revoking spender to spend token...")
output = send_contract_tx(
self.app,
signer,
signer.functions["approve"](spender, 0),
)
# Print output
render(self.app, output)
@ex(
help="Show the decimals of the given token",
arguments=[
(["token"], {"help": "Token to check, by name"}),
*args.chain_and_rpc(),
],
)
def decimals(self) -> None:
client = make_contract_client(self.app, self.app.pargs.token)
decimals = client.functions["decimals"]().call()
render(self.app, decimals)
@ex(
help="Show the balance of the given token for the given address",
arguments=[
(["token"], {"help": "Token to check, by name"}),
(["address"], {"help": "Address or name of the account to check"}),
(["--wei"], {"help": "Print the output in wei", "action": "store_true"}),
args.block(),
*args.chain_and_rpc(),
],
)
def balance(self) -> None:
address = resolve_address(self.app.pargs.address, chain=self.app.chain.name)
client = make_contract_client(self.app, self.app.pargs.token)
block = args.parse_block(self.app, "block")
balance_in_wei = client.functions["balanceOf"](address).call(
block_identifier=block
)
if self.app.pargs.wei:
render(self.app, balance_in_wei)
else:
balance = balance_in_wei / decimal.Decimal(
10 ** client.functions["decimals"]().call(block_identifier=block)
)
render(self.app, balance)
@ex(
help="Return the allowance of the given spender to spend the given token for the given address",
arguments=[
(["token"], {"help": "Token to check, by name"}),
(["owner"], {"help": "Address or name of the account to check"}),
(["spender"], {"help": "Address or name of the spender to check"}),
args.block(),
*args.chain_and_rpc(),
],
)
def allowance(self) -> None:
# Parse arguments
spender = resolve_address(self.app.pargs.spender, chain=self.app.chain.name)
owner = resolve_address(self.app.pargs.owner, chain=self.app.chain.name)
block = args.parse_block(self.app, "block")
# Initialize client
client = make_contract_client(self.app, self.app.pargs.token)
decimals = client.functions["decimals"]().call(block_identifier=block)
allowance_in_wei = client.functions["allowance"](owner, spender).call(
block_identifier=block
)
allowance = allowance_in_wei / 10**decimals
render(self.app, allowance)
@ex(help="Transfer tokens. Not implemented yet. Use `w3 send` instead.")
def transfer(self) -> None:
self.app.log.warning("Not implemented yet. Use `w3 send` instead.")
# ____ _
# / ___| _ __ _ _ __| |
# | | | '__| | | | | / _` |
# | |___ | | | |_| | | (_| |
# \____| |_| \__,_| \__,_|
@ex(
help="show details of token by name and optionally chain",
arguments=[
(["name"], {"help": "name of the token"}),
args.chain(),
],
)
def get(self) -> None:
try:
contract = Contract.get_by_name_chain_and_types_or_raise(
self.app.pargs.name, self.app.chain.name, ["erc20", "weth"]
)
except ContractNotFound:
raise ContractNotFound(
f"Could not find a token named '{self.app.pargs.name}' on chain '{self.app.chain.name}'"
)
render(self.app, model_to_dict(contract))
@ex(
help="add a new token to the database",
arguments=[
(["name"], {"help": "name of the token"}),
(["-d", "--desc"], {"action": "store"}),
(
["address"],
{"help": "address of the contract on the blockchain (0x...)"},
),
(
["--weth"],
{
"help": "if the token is a wrapped native token, set this flag",
"action": "store_true",
},
),
(
["-u", "--update"],
{
"help": "if a contract with the same name is present, overwrite it",
"action": "store_true",
},
),
args.chain(),
],
)
def add(self) -> None:
# Add or update contract
contract = Contract.get_by_name_and_chain(
self.app.pargs.name, self.app.chain.name
)
if not contract or self.app.pargs.update:
Contract.upsert(
{
"name": self.app.pargs.name,
"desc": self.app.pargs.desc,
"type": "weth" if self.app.pargs.weth else "erc20",
"address": self.app.pargs.address,
"chain": self.app.chain.name,
},
logger=self.app.log.info,
)
else:
raise Web3CliError(
f"Contract '{self.app.pargs.name}' already exists. Use `--update` or `-u` to update it."
)
@ex(help="list tokens registered in the database", arguments=[args.chain()])
def list(self) -> None:
render_table(
self.app,
data=[
[c.name, c.chain, c.type, "Yes" if bool(c.abi) else "No", c.address]
for c in Contract.get_all(Contract.name)
if c.chain == self.app.chain.name and c.type in ("erc20", "weth")
],
headers=["NAME", "CHAIN", "TYPE", "ABI", "ADDRESS"],
wrap=42,
)
@ex(
help="delete a token from the database",
arguments=[(["name"], {"help": "name of the token to delete"}), args.chain()],
)
def delete(self) -> None:
contract = Contract.get_by_name_chain_and_types_or_raise(
self.app.pargs.name, self.app.chain.name, ["erc20", "weth"]
)
contract.delete_instance()
self.app.log.info(
f"Contract '{self.app.pargs.name}' on chain '{self.app.chain.name}' deleted correctly"
)