code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
def add (a,b):
return a+b
def squared(x):
return x**2
| 0411-test | /0411_test-1.0.1-py3-none-any.whl/mycalc/calculator.py | calculator.py |
def print_lol(the_list,level)
for each_item in the_list
if isinstance(each_item,list)
print_lol(each_item,level + 1)
else
for tab_step in range(level)
print "\t",
print each_item
| 0805nexter | /0805nexter-1.2.0.zip/0805nexter-1.2.0/0805nexter.py | 0805nexter.py |
from distutils.core import setup
setup(
name = '0805nexter',
version = '1.2.0',
py_modules = ['0805nexter'],
author = 'hgtkpython',
author_email = '2868989685@qq.com',
url = 'http://www.hp.com',
description = 'a simple printer of nested lest',
)
| 0805nexter | /0805nexter-1.2.0.zip/0805nexter-1.2.0/setup.py | setup.py |
from setuptools import setup
setup(
name='0FELA',
version='66.0.0',
author='Yandex',
author_email='security@yandex-team.ru',
url='https://ya.ru',
description='A package to prevent Dependency Confusion attacks against Yandex',
)
| 0FELA | /0FELA-66.0.0.tar.gz/0FELA-66.0.0/setup.py | setup.py |
# -*- coding: utf-8 -*-
import sys
import pexpect
import signal
import yaml
import os
import shutil
import time
import termios
import struct
import fcntl
password_yaml = """ssh:
- id: 1
name: demo1
user: fqiyou
password: xxx
host: 1.1.1.1
port: 20755
- id: 2
name: demo2
user: fqiyou
password: xxx
host: 1.1.1.1
port: 39986
- id: 3
name: demo3
user: root
password: demo.pem
host: 1.1.1.1
port: 22
"""
keys_demo_pem = """-----BEGIN RSA PRIVATE KEY-----
xxxxx
-----END RSA PRIVATE KEY-----
"""
child = None
termios_size = None
def _sigwinch_passthrough(sig, data):
global child,termios_size
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1074295912
s = struct.pack("HHHH", 0, 0, 0, 0)
a = struct.unpack('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s))
termios_size = a
if child is not None:
child.setwinsize(a[0], a[1])
def _exit(*args, **kwargs):
print('You choose to stop so.')
if child is not None:
child.close()
sys.exit(1)
def _get_hosts_by_config():
try:
so_dir = os.path.join(os.path.expanduser('~'), ".so")
password_yaml_file = os.path.join(so_dir, "password.yaml")
keys_dir = os.path.join(so_dir, "keys")
return yaml.load(open(password_yaml_file, 'r').read(), Loader=yaml.Loader)["ssh"], keys_dir
except Exception as e:
print("获取配置文件错误", e)
exit(1)
return
def _login_ssh(user, password, host, port):
global child
if password.endswith('.pem'):
child = pexpect.spawn('ssh %s@%s -p %s -i %s' % (user, host, port, password))
else:
child = pexpect.spawn('ssh %s@%s -p %s' % (user, host, port))
i = child.expect(['nodename nor servname provided', 'Connection refused', pexpect.TIMEOUT, '[Pp]assword:', 'continue connecting (yes/no)?', '#'])
if i <= 2:
print(child.before, child.after)
return
elif i == 3:
child.sendline(password)
elif i == 4:
child.sendline('yes')
child.expect('[Pp]assword:')
child.sendline(password)
elif i == 5:
pass
else:
print(i)
print(child.before, child.after)
return
print('Login Success!')
child.sendline('')
_sigwinch_passthrough(None,None)
if termios_size is not None:
child.setwinsize(termios_size[0], termios_size[1])
child.interact()
def _print_head():
print("##############################################")
print("\033[0;36m SU Login Platform \033[0m")
print("##############################################")
def _print_underline():
print("----------------------------------------------")
def _print_remind():
print("[*] 选择主机:")
def _get_cmd_args():
remind = "[*] 选择主机:"
args = ""
if 2 == sys.version_info[0]:
args = raw_input(remind)
elif 3 == sys.version_info[0]:
args = input(remind)
else:
_print_remind()
args = sys.stdin.readline()
return str(args).replace("\n", "")
def _print_host_list(host_list):
_print_underline()
print(" 序号 | 主机 | 说明 " )
_print_underline()
for i in host_list:
print("\033[0;31m%4s\033[0m\t| %15s | %s\t" % (i['id'], i['host'], i['name']))
_print_underline()
def _login(info, keys_dir):
user = info["user"]
password = info["password"]
host = info["host"]
port = info["port"]
if password.endswith('.pem'):
password = os.path.join(keys_dir,password)
_login_ssh(user=user, password=password, host=host, port=port)
def run():
config_host_list, key_dir = _get_hosts_by_config()
config_host_map = dict(zip([str(i["id"]) for i in config_host_list], config_host_list))
# 信号
signal.signal(signal.SIGINT, _exit)
signal.signal(signal.SIGTERM, _exit)
signal.signal(signal.SIGWINCH, _sigwinch_passthrough)
_print_head()
while True:
_print_host_list(config_host_list)
# _print_remind()
# cmd_args = sys.stdin.readline().replace("\n", "")
cmd_args = _get_cmd_args()
if cmd_args in config_host_map:
_login(config_host_map[cmd_args], key_dir)
elif cmd_args == "q" or cmd_args == "exit" or cmd_args == "quit":
_exit()
return
else:
print("未知参数:%s" % cmd_args)
def run_install():
so_dir = os.path.join(os.path.expanduser('~'), ".so")
if os.path.exists(so_dir):
shutil.move(so_dir, so_dir+"_" + str(int(time.time() * 1000)))
os.mkdir(so_dir)
os.mkdir(os.path.join(so_dir, "keys"))
with open(os.path.join(so_dir, 'password.yaml'), 'w') as f:
f.write(password_yaml)
with open(os.path.join(so_dir, "keys", 'demo.pem'), 'w') as f:
f.write(password_yaml)
| 0lever-so | /0lever_so-1.1.2-py3-none-any.whl/so/so.py | so.py |
======
so
======
This is a SSH login tool
Installation
============
::
pip install --upgrade 0lever-so
or
pip install --upgrade 0lever-so -i https://pypi.org/simple/
Usage
=====
::
# 初始化配置文件,升级无需初始化,chmod 400 ~/.so/keys/*
➜ ~ so_install
➜ ~ cd .so
➜ .so tree
.
├── keys
│ └── demo.pem
└── password.yaml
1 directory, 2 files
➜ .so
::
# 配置文件
ssh:
- id: 1
name: demo1
user: fqiyou
password: xxx
host: 1.1.1.1
port: 20755
- id: 2
name: demo2
user: fqiyou
password: xxx
host: 1.1.1.1
port: 39986
- id: 3
name: demo3
user: root
password: demo.pem
host: 1.1.1.1
port: 22
Other-shell
=====
::
#!/usr/bin/expect
set USER "xxx"
set PASSWD "xxx"
set timeout 10
trap {
set rows [stty rows]
set cols [stty columns]
stty rows $rows columns $cols < $spawn_out(slave,name)
} WINCH
spawn su - $USER
expect "Password: "
send "$PASSWD\n"
interact
::
#!/usr/bin/expect -f
set HOST [lindex $argv 0]
set USER [lindex $argv 1]
set PASSWD [lindex $argv 2]
set PORT [lindex $argv 3]
set timeout 10
trap {
set rows [stty rows]
set cols [stty columns]
stty rows $rows columns $cols < $spawn_out(slave,name)
} WINCH
spawn ssh $USER@HOST -p $PORT
expect {
"*yes/no" {send "yes\r"; exp_continue}
"*password:" {send "$PASSWD\r"}
}
interact
```
| 0lever-so | /0lever_so-1.1.2-py3-none-any.whl/0lever_so-1.1.2.dist-info/DESCRIPTION.rst | DESCRIPTION.rst |
# -*- coding:utf-8 -*-
import requests
import json
class DingDing(object):
def __init__(self, access_token):
self._url = "https://oapi.dingtalk.com/robot/send"
self._access_token = access_token
def _do(self, payload):
querystring = {"access_token": self._access_token}
headers = {'Content-Type': "application/json"}
response = requests.request("POST", self._url, data=json.dumps(payload), headers=headers, params=querystring)
return response.text
def send_text(self, content, at=[]):
payload = \
{
'msgtype': 'text',
'text': {
'content': content
},
'at': {
'atMobiles': at,
'isAtAll': False
}
}
return self._do(payload=payload)
def send_link(self, title, text, messageUrl, picUrl=""):
payload = \
{
"msgtype": "link",
"link": {
"text": text,
"title": title,
"picUrl": picUrl,
"messageUrl": messageUrl
}
}
return self._do(payload=payload)
def send_markdown(self, title, text, at=[], messageUrl="", picUrl=""):
payload = \
{
"msgtype": "markdown",
"markdown": {
"title": title,
"text": "### {title} \n> {at}\n\n> {text}\n > ![]({picUrl})\n > ###### [详情]({messageUrl}) ".format(
title=title,
text=text,
at=",".join(map(lambda x:"@{at}".format(at=x),at)),
picUrl=picUrl,
messageUrl=messageUrl
)
},
"at": {
"atMobiles": at,
"isAtAll": False
}
}
print payload
return self._do(payload=payload)
def send_actioncard(self, title, text, messageUrl="", picUrl=""):
payload = \
{
"actionCard": {
"title": title,
"text": "![]({picUrl}) \n #### {title} \n\n {text}".format(picUrl=picUrl, title=title, text=text),
"hideAvatar": "0",
"btnOrientation": "0",
"singleTitle": "阅读详情",
"singleURL": messageUrl
},
"msgtype": "actionCard"
}
return self._do(payload=payload)
def send_different_actitioncard(self, title, text, title_url_tuple_list=[], picUrl=""):
title_url_dict_list = [{"title": i[0], "actionURL": i[1]} for i in title_url_tuple_list]
payload = \
{
"actionCard": {
"title": title,
"text": "![]({picUrl}) \n\n #### {title} \n\n {text}".format(picUrl=picUrl, title=title, text=text),
"hideAvatar": "0",
"btnOrientation": "0",
"btns": title_url_dict_list
},
"msgtype": "actionCard"
}
return self._do(payload=payload)
def send_feedcard(self, title_msg_pic_tuple_list):
title_msg_pic_dict_list = [{"title": i[0], "messageURL": i[1], "picURL": i[2]} for i in title_msg_pic_tuple_list]
payload = \
{
"feedCard": {
"links": title_msg_pic_dict_list
},
"msgtype": "feedCard"
}
return self._do(payload=payload)
| 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/alarm/dingding.py | dingding.py |
# -*- coding:utf-8 -*-
from dingding import DingDing
| 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/alarm/__init__.py | __init__.py |
# -*- coding:utf-8 -*-
from impala_helper import Db
import pandas as pd
class Hive(Db):
def __init__(self, *args, **kwargs):
self._host = kwargs["host"]
self._port = kwargs["port"] if "port" in kwargs else 10000
self._user = kwargs["user"] if "user" in kwargs else None
self._password = kwargs["password"] if "password" in kwargs else None
# self._auth_mechanism = "LDAP"
self._auth_mechanism = "PLAIN"
def execute(self, sql, is_ddl=True):
try:
self._engine = self._engine if self._engine is not None else self.init_engine()
cursor = self._engine.execute("select 1").cursor
cursor.execute(sql, configuration=self._configuration)
if is_ddl:
return None, None
if cursor:
columns = [metadata[0] for metadata in cursor.description]
data = cursor.fetchall()
df = pd.DataFrame(data=data, columns=columns)
return df, None
else:
return None, None
except Exception, e:
return None, e | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/db/hive_helper.py | hive_helper.py |
# -*- coding:utf-8 -*-
import sqlalchemy
import pandas as pd
import sqlalchemy.orm as sqlalchemy_orm
from impala.dbapi import connect
class Db(object):
_engine = None
_session = None
_configuration = None
def __init__(self, *args, **kwargs):
self._host = kwargs["host"]
self._port = kwargs["port"]
self._user = kwargs["user"] if "user" in kwargs else None
self._password = kwargs["password"] if "password" in kwargs else None
self._auth_mechanism = "NOSASL"
def _creator(self):
return connect(host=self._host,
port=self._port,
user=self._user,
password=self._password,
auth_mechanism=self._auth_mechanism)
def creator(self):
return connect(host=self._host,
port=self._port,
user=self._user,
password=self._password,
auth_mechanism=self._auth_mechanism)
def init_engine(self):
self._engine = sqlalchemy.create_engine('impala://', echo=True,
creator=self._creator, max_overflow=100,
pool_size=100, pool_timeout=180, )
return self._engine
def init_session(self):
self._engine = self._engine if self._engine is not None else self.init_engine()
self._session = sqlalchemy_orm.scoped_session(lambda: sqlalchemy_orm.create_session(bind=self._engine))()
return self._session
def get_engine(self):
self._engine = self._engine if self._engine is not None else self.init_engine()
return self._engine
def get_session(self):
self._session = self._session if self._session is not None else self.init_session()
return self._session
def execute(self, sql):
try:
self._engine = self._engine if self._engine is not None else self.init_engine()
cursor = self._engine.execute(sql).cursor
if cursor:
columns = [metadata[0] for metadata in cursor.description]
data = cursor.fetchall()
df = pd.DataFrame(data=data, columns=columns)
return df, None
else:
return None, None
except Exception, e:
return None, e
def set_configuration(self, configuration):
self._configuration = configuration
def close(self):
if self._session:
self._session.close()
class Impala(Db):
def __init__(self, *args, **kwargs):
self._host = kwargs["host"]
self._port = kwargs["port"] if "port" in kwargs else 21050
self._user = kwargs["user"] if "user" in kwargs else None
self._password = kwargs["password"] if "password" in kwargs else None
# self._auth_mechanism = "PLAIN"
self._auth_mechanism = "NOSASL"
| 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/db/impala_helper.py | impala_helper.py |
# -*- coding: utf-8 -*-
from functools import wraps
import hashlib
import logging
import json
import redis
class MyRedis(object):
def __init__(self, host, port, password,db=0):
self.pool = redis.ConnectionPool(host=host, password=password, port=port, db=db)
self.rs = redis.Redis(connection_pool=self.pool, db=db)
def get_redis(self):
return self.rs
def redising(time=0, redis_key_prefix="_lever_utils", db=None):
'''
redis 装饰器
:param time: 保留时常
# time==0,则不走缓存;
# time>0,则走缓存,缓存时间为time;
# time==-1,则走缓存,缓存时间为永久.
# time==-2,则每次现查,并永久缓存覆盖现有缓存
:param redis_key: redis key
:return:
'''
def func_wrapper(func):
@wraps(func)
def return_wrapper(*args, **kwargs):
if time == 0 or db is None:
return func(*args, **kwargs), None
func_info_str = "model[%s]\t func[%s]\t file[%s][%s]\t args[%s]\t kwargs[%s]" % (func.__module__
, func.__name__
, func.func_code.co_filename
, func.func_code.co_firstlineno
, args
, kwargs)
m2 = hashlib.md5()
m2.update(func_info_str.encode('utf-8'))
func_info_str_md5 = m2.hexdigest()
func_info_str_md5_redis_key = redis_key_prefix+"-"+func_info_str_md5
redis_store = db
if time == -1 or time > 0:
redis_result = redis_store.get(func_info_str_md5_redis_key)
if redis_result is None:
func_result = func(*args, **kwargs)
redis_store.set(func_info_str_md5_redis_key, json.dumps(func_result), time if time > 0 else None)
else:
logging.info("to-redis:key[%s]" % func_info_str_md5_redis_key)
func_result = json.loads(redis_result)
else:
func_result = func(*args, **kwargs)
redis_store.set(func_info_str_md5_redis_key, json.dumps(func_result))
return func_result, func_info_str_md5_redis_key
return return_wrapper
return func_wrapper | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/db/redis_helper.py | redis_helper.py |
# -*- coding: utf-8 -*-
from redis_helper import redising
import elasticsearch
class MyElasticsearch(elasticsearch.Elasticsearch):
redis_db = None
def __init__(self, *args, **kwargs):
self.redis_db = kwargs.pop("redis_db")
elasticsearch.Elasticsearch.__init__(self, *args, **kwargs)
@elasticsearch.client.utils.query_params('_source', '_source_exclude', '_source_include',
'allow_no_indices', 'allow_partial_search_results', 'analyze_wildcard',
'analyzer', 'batched_reduce_size', 'default_operator', 'df',
'docvalue_fields', 'expand_wildcards', 'explain', 'from_',
'ignore_unavailable', 'lenient', 'max_concurrent_shard_requests',
'pre_filter_shard_size', 'preference', 'q', 'request_cache', 'routing',
'scroll', 'search_type', 'size', 'sort', 'stats', 'stored_fields',
'suggest_field', 'suggest_mode', 'suggest_size', 'suggest_text',
'terminate_after', 'timeout', 'track_scores', 'track_total_hits',
'typed_keys', 'version')
def search(self, *args, **kwargs):
redis_db = self.redis_db
redis_key_prefix_default = kwargs.pop("redis_key_prefix") if kwargs.has_key(
"redis_key_prefix") else "_lever_utils"
redis_key_time_default = kwargs.pop("redis_key_time") if kwargs.has_key(
"redis_key_time") else 0
kwargs["request_timeout"] = 300
kwargs["timeout"] = '600s'
@redising(db=redis_db, time=redis_key_time_default, redis_key_prefix=redis_key_prefix_default)
def query(*query_args, **query_kwargs):
result = elasticsearch.Elasticsearch.search(self, *query_args, **query_kwargs)
return result
if self.redis_db is None:
query_result, query_result_redis_key = elasticsearch.Elasticsearch.search(self, *args, **kwargs), None
else:
query_result, query_result_redis_key = query(*args, **kwargs)
return query_result | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/db/es_helper.py | es_helper.py |
# -*- coding:utf-8 -*-
from redis_helper import redising, MyRedis as Redis
from es_helper import MyElasticsearch as ES
| 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/db/__init__.py | __init__.py |
# -*- coding:utf-8 -*-
import sqlalchemy
import sqlalchemy.orm as sqlalchemy_orm
import pandas as pd
from sshtunnel import SSHTunnelForwarder
class Mysql(object):
_engine = None
_session = None
_ssh_server = None
def __init__(self, *args, **kwargs):
user = kwargs["user"]
password = kwargs["password"]
host = kwargs["host"]
port = kwargs["port"]
db = kwargs["db"] if "db" in kwargs else ""
is_ssh = kwargs["is_ssh"] if "is_ssh" in kwargs else False
if is_ssh:
ssh_host = kwargs["ssh_host"]
ssh_post = kwargs["ssh_post"]
ssh_user = kwargs["ssh_user"]
ssh_password = kwargs["ssh_password"]
self._ssh_server = SSHTunnelForwarder(
(ssh_host, int(ssh_post)),
ssh_username=ssh_user,
ssh_password=ssh_password,
remote_bind_address=(host, int(port)))
self._ssh_server.start()
self._url = "mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8mb4" \
% (user, password, '127.0.0.1', self._ssh_server.local_bind_port, db)
else:
self._url = "mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8mb4" % (user, password, host, port, db)
def init_engine(self):
self._engine = sqlalchemy.create_engine(self._url, echo=False, encoding="utf-8")
return self._engine
def init_session(self):
self._engine = self._engine if self._engine is not None else self.init_engine()
self._session = sqlalchemy_orm.scoped_session(sqlalchemy_orm.sessionmaker(bind=self._engine))()
return self._session
def get_engine(self):
self._engine = self._engine if self._engine is not None else self.init_engine()
return self._engine
def get_session(self):
self._session = self._session if self._session is not None else self.init_session()
return self._session
def close(self):
if self._session:
self._session.close()
if self._ssh_server:
self._ssh_server.close()
def execute(self, sql):
try:
if not self._engine:
self.init_engine()
result = self._engine.execute(sql)
cursor = result.cursor
if cursor:
columns = [metadata[0] for metadata in cursor.description]
data = cursor.fetchall()
data = list(data)
df = pd.DataFrame(data=data, columns=columns)
return df, None
else:
return None, None
except Exception, e:
return None, e
| 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/db/mysql_helper.py | mysql_helper.py |
# -*- coding:utf-8 -*-
from datetime import datetime, timedelta
def get_time(num=0, sf="%Y%m%d",unit="days"):
'''
得到时间字符串
:param num: 和unit配合使用计算时间
:param sf: %Y%m%d%H%M%S
:param unit: days = None, seconds = None, microseconds = None, milliseconds = None, minutes = None, hours = None, weeks = None
:return: %Y%m%d%H%M%S 格式化时间
'''
arr = None
exec "arr={'%s':%s}" % (unit, int(num))
return str((datetime.today() + timedelta(**arr)).strftime(sf))
def get_certain_time(log_day, log_day_sf="%Y%m%d", num=0, sf="%Y%m%d", unit="days"):
'''
得到指定时间字符串
:param log_day: 时间
:param log_day_sf: 时间format
:param num: 和unit配合使用计算时间
:param sf: %Y%m%d%H%M%S
:param unit: days = None, seconds = None, microseconds = None, milliseconds = None, minutes = None, hours = None, weeks = None
:return: %Y%m%d%H%M%S 格式化时间
'''
arr = None
exec "arr={'%s':%s}" % (unit, int(num))
return str((datetime.strptime(log_day, log_day_sf) + timedelta(**arr)).strftime(sf))
def format_time(log_date, sf="%Y%m%d", new_sf="%Y-%m-%d"):
'''
格式化时间
:param log_date: 字符串日期
:param sf: %Y%m%d%H%M%S
:param new_sf: %Y%m%d%H%M%S
:return: 字符串日期
'''
return datetime.strptime(log_date, sf).strftime(new_sf) | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/time/__init__.py | __init__.py |
# -*- coding:utf-8 -*-
import oss2
class Oss(object):
def __init__(self, access_key_id, access_key_secret, endpoint, bucket_name):
auth = oss2.Auth(access_key_id, access_key_secret)
self._endpoint = endpoint
self._bucket_name = bucket_name
self._bucket = oss2.Bucket(auth, endpoint, bucket_name)
def upload(self, src_path, dst_path):
self._bucket.put_object_from_file(dst_path, src_path)
return self._get_oss_url(dst_path)
def upload_data(self, data, dst_path):
self._bucket.put_object(dst_path, data)
return self._get_oss_url(dst_path)
def append_data(self, data, dst_path):
try:
oss_file = self._get_oss_object(dst_path)
position = oss_file.content_length
except oss2.exceptions.NoSuchKey:
self._bucket.object_exists(dst_path)
position = 0
except:
raise
self._bucket.append_object(position=position, key=dst_path, data=data)
return self._get_oss_object(dst_path)
def delete(self, dst_path):
return self._bucket.delete_object(dst_path)
def _get_oss_url(self, dst_path):
return "https://%s.%s/%s" % (self._bucket_name, self._endpoint.split("//")[-1], dst_path)
def _get_oss_object(self, dst_path):
return self._bucket.get_object(dst_path) | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/file/oss_helper.py | oss_helper.py |
# -*- coding:utf-8 -*-
import pandas as pd
import os
class Excel(object):
DEFAULT = 0
RIGHT = 1
DOWN = 2
def __init__(self):
pass
def _check_file(self, filename):
file_dir = filename.rsplit(os.sep, 1)[0]
if not os.path.exists(file_dir) and file_dir != filename:
os.makedirs(file_dir)
def dfs2excel(self, dfs, filename, sheetnames=[], connect_type=DEFAULT, gap=1):
"""
dataframe数组写excel
:param dfs: dataframe数组
:param filename: excel文件名
:param sheetnames: sheet页名称数组
:param connect_type: excel连接方向
:param gap: 行列间隙
:return: filename
"""
try:
self._check_file(filename)
sheetname_iter = iter(sheetnames)
excelWrite = pd.ExcelWriter(filename)
start = 0
for i in range(len(dfs)):
df = dfs[i]
if i == 0 or connect_type == Excel.DEFAULT:
sheetname = next(sheetname_iter, "Sheet{index}".format(index=i))
params = dict(excel_writer=excelWrite, sheet_name=sheetname, index=False)
if connect_type == Excel.RIGHT:
params["startcol"] = start
start += df.shape[1] + gap
elif connect_type == Excel.DOWN:
params["startrow"] = start
start += df.shape[0] + gap + 1
df.to_excel(**params)
excelWrite.save()
return filename
except Exception as e:
print(e)
return None
'''
# demo
df = pd.DataFrame({"a": [1, 2, 3]})
df1 = pd.DataFrame({"b": [2, 3, 4]})
dfs = [df, df1]
excel = Excel()
excel.dfs2excel(dfs, "aa/bb/cc/default.xlsx", ["a", "b"])
excel.dfs2excel(dfs, "aa/bb/cc/right.xlsx", ["a", "b"], Excel.RIGHT)
excel.dfs2excel(dfs, "aa/bb/cc/down.xlsx", ["a", "b"], Excel.DOWN)
''' | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/file/excel_helper.py | excel_helper.py |
# -*- coding:utf-8 -*-
from oss_helper import Oss | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/file/__init__.py | __init__.py |
# -*- coding:utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import os
import poplib
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from datetime import datetime
class Mail(object):
def __init__(self, server, port, username, password, sender):
self._server = server
self._port = port
self._username = username
self._password = password
self._sender = sender
def send(self, subject, to, cc=[], text=None, html=None, files=[]):
try:
# 构造邮件对象MIMEMultipart对象
# mixed为附件邮件类型
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = self._sender
msg['To'] = ";".join(to)
msg['Cc'] = ";".join(cc)
mime_text = MIMEText(html, 'html', 'utf-8') if html is not None else MIMEText(text, 'plain', 'utf-8')
msg.attach(mime_text)
for file in files:
if isinstance(file, str):
file = file.decode("utf-8")
basename = os.path.basename(file)
# 构造附件
sendfile = open(file, 'rb').read()
text_att = MIMEText(sendfile, 'base64', 'utf-8')
text_att["Content-Type"] = 'application/octet-stream'
text_att["Content-Disposition"] = 'attachment; filename=%s' % basename.encode("gb2312")
msg.attach(text_att)
# 发送邮件
smtp = smtplib.SMTP_SSL(self._server, self._port)
smtp.set_debuglevel(0)
smtp.ehlo()
smtp.login(self._username, self._password)
err = smtp.sendmail(self._sender, to+cc, msg.as_string())
smtp.close()
if not err:
send_result = True, None
else:
send_result = False, err
except Exception, e:
send_result = False, e
return send_result
class MailServer(object):
SF = "%Y-%m-%d %H:%M:%S"
pop3_server = None
args_pop_server = None
args_user = None
args_password = None
def __init__(self, pop_server, user, password):
self.args_pop_server = pop_server
self.args_user = user
self.args_password = password
self._restart()
def quit(self):
if self.pop3_server is not None:
self.pop3_server.quit()
self.pop3_server = None
def _restart(self):
self.quit()
tmp_pop3_server = poplib.POP3(self.args_pop_server)
tmp_pop3_server.user(self.args_user)
tmp_pop3_server.pass_(self.args_password)
self.pop3_server = tmp_pop3_server
def get(self, *args):
self._restart()
res = {}
for arg in args:
if arg == 'stat':
res[arg] = self.pop3_server.stat()[0]
elif arg == 'list':
res[arg] = self.pop3_server.list()
elif arg == 'latest':
mails = self.pop3_server.list()[1]
resp, lines, octets = self.pop3_server.retr(len(mails))
msg = Parser().parsestr(b'\r\n'.join(lines))
res[arg] = self._parse_message(msg)
elif type(arg) == int:
mails = self.pop3_server.list()[1]
if arg > len(mails):
res[arg] = None
continue
resp, lines, octets = self.pop3_server.retr(arg)
msg = Parser().parsestr(b'\r\n'.join(lines))
res[arg] = self._parse_message(msg)
else:
res[arg] = None
return res
def _parse_message(self, msg):
result = {}
# Subject
subject_tmp = msg.get('Subject', '')
value, charset = decode_header(subject_tmp)[0]
if charset:
value = value.decode(charset)
result['Subject'] = value
# 'From', 'To', 'Cc'
for header in ['From', 'To', 'Cc']:
result[header] = []
temp = msg.get(header, '')
temp_list = temp.split(',')
for i in temp_list:
if i == '':
continue
name, addr = parseaddr(i)
value, charset = decode_header(name)[0]
if charset:
value = value.decode(charset)
tmp_addr_info = dict(name=value, addr=addr)
result[header].append(tmp_addr_info)
try:
result['Date'] = datetime.strptime(msg.get('Date', ''), "%a, %d %b %Y %H:%M:%S +0800").strftime(self.SF)
except Exception,e:
result['Date'] = str(msg.get('Date', ''))
result['Files'] = []
result['Bodys'] = []
for par in msg.walk():
name = par.get_filename()
if name:
data = par.get_payload(decode=True)
result['Files'].append(dict(name=name, data=data))
else:
body = par.get_payload(decode=True)
if body is not None:
result['Bodys'].append(dict(body=body))
return result
| 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/mail/mail_helper.py | mail_helper.py |
# -*- coding:utf-8 -*-
from mail_helper import MailServer
import time
# pip install --upgrade 0lever-utils -i https://pypi.org/simple/
def test():
ms = MailServer('smtp.exmail.qq.com', 'xx@xx.com', '')
# 获取最新邮件序号
print ms.get('stat')
# 获取序号list
print ms.get('list')
# 指定序号获取邮件
print ms.get(1, 2, ms.get('stat')['stat'])
last_mail_info = ""
while True:
# 获取最新一封邮件
result = ms.get('latest')
latest_result = result["latest"]
tmp = latest_result["Date"] + latest_result["Subject"]
if tmp != last_mail_info:
print "-----------------" * 10
print "Subject:\n\t",
print latest_result["Subject"]
print "Date:\n\t",
print latest_result["Date"]
print "From:\n\t",
print latest_result["From"]
print "To:\n\t",
print latest_result["To"]
print "Cc:\n\t",
print latest_result["Cc"]
print "Files:\n",
latest_result_files = latest_result["Files"]
for latest_result_file in latest_result_files:
print "\t" + latest_result_file["name"]
# with open("/Users/chaoyang/tmp/"+latest_result_file["name"], 'w') as f:
# f.write(latest_result_files[0]["data"])
print "Bodys:\n",
latest_result_bodys = latest_result["Bodys"]
for latest_result_body in latest_result_bodys:
print "\t", "xxx"
# print latest_result_body["body"]
last_mail_info = tmp
time.sleep(2)
ms.quit()
if __name__ == '__main__':
# test()
pass | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/mail/mail_helper_test.py | mail_helper_test.py |
# -*- coding:utf-8 -*-
from mail_helper import Mail | 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/_lever_utils/foo/helpers/mail/__init__.py | __init__.py |
UNKNOWN
| 0lever-utils | /0lever_utils-0.1.6-py3-none-any.whl/0lever_utils-0.1.6.dist-info/DESCRIPTION.rst | DESCRIPTION.rst |
Hello, ZERO
===========
Usage
-----
`pip install 0proto`
Then, simply use the command periodically:
`0proto https://example.com/something/etc`
This will save data to:
`settings.BASE_DIR/data/0proto-DOMAIN:default/Item`
N-Spacing
---------
If you want to seprate different sessions and sources, just use name param:
`0proto URI --name Name`
This will save to:
`settings.BASE_DIR/data/0proto-DOMAIN:Name/Type`
The `--name` value can be arbitray filesystem-compatible filename sub-string, so, you can use it to separate data by accounts, languages, or other features.
**NOTE**: Corresponding auth and session data will be stored in `settings.BASE_DIR/sessions` folder.
Saving to specific DIR
----------------------
Saving to custom folder simply pass `--path` parameter, like:
`0proto URI --name Name --path /home/mindey/Desktop/mydata`
| 0proto | /0proto-0.0.2.tar.gz/0proto-0.0.2/README.md | README.md |
from setuptools import find_packages, setup
with open('README.md', 'r', encoding='utf-8') as f:
long_description = f.read()
setup(
name='0proto',
version='0.0.2',
description='Simple PROTO data saver.',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/example/0proto',
author='Mindey',
author_email='~@example.com',
license='MIT',
packages = find_packages(exclude=['docs', 'tests*']),
install_requires=[
'metaform',
'metatype',
'typer',
],
extras_require = {
'test': ['coverage', 'pytest', 'pytest-cov'],
},
zip_safe=False,
entry_points = {
'console_scripts': [
'0proto=0proto.main:app'
],
}
)
| 0proto | /0proto-0.0.2.tar.gz/0proto-0.0.2/setup.py | setup.py |
ハロー・ゼロ
============
使い方
------
`pip install 0rest`
| 0rest | /0rest-0.0.0.tar.gz/0rest-0.0.0/README.md | README.md |
from setuptools import find_packages, setup
with open('README.md', 'r', encoding='utf-8') as f:
long_description = f.read()
setup(
name='0rest',
version='0.0.0',
description='Simple REST API data saver.',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/0oio/0rest',
author='Mindey',
author_email='~@mindey.com',
license='MIT',
packages = find_packages(exclude=['docs', 'tests*']),
install_requires=[
'metaform',
'metatype',
'typer',
],
extras_require = {
'test': ['coverage', 'pytest', 'pytest-cov'],
},
zip_safe=False,
entry_points = {
'console_scripts': [
'0rest=0rest.main:app'
],
}
)
| 0rest | /0rest-0.0.0.tar.gz/0rest-0.0.0/setup.py | setup.py |
ハロー・ゼロ
============
使い方
------
`pip install 0rss`
Then, simply use the command periodically:
`0rss https://0oo.li/feed/en`
This will save data periodically, to:
`~/.metadrive/data/0rss-0oo.li:default/Post`
多源用法
--------
If you want to seprate different sessions and sources, just use name param:
`0rss https://0oo.li/feed/en --name mindey@example.com`
This will save to:
`~/.metadrive/data/0rss-0oo.li:mindey@example.com/Post`
The `--name` value can be arbitray filesystem-compatible filename sub-string, so, you can use it to separate data by accounts, languages, or other features.
**NOTE**: Corresponding auth and session data will be stored in `~/.metadrive/sessions` folder.
指定したフォルダーへ保存
------------------------
Saving to custom folder simply pass `--path` parameter, like:
`0rss https://hub.baai.ac.cn/rss --name Mindey --path /home/mindey/Desktop/mydata`
| 0rss | /0rss-1.0.2.tar.gz/0rss-1.0.2/README.md | README.md |
from setuptools import find_packages, setup
with open('README.md', 'r', encoding='utf-8') as f:
long_description = f.read()
setup(
name='0rss',
version='1.0.2',
description='Simple RSS data saver.',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/mindey/0rss',
author='Mindey',
author_email='~@mindey.com',
license='MIT',
packages = find_packages(exclude=['docs', 'tests*']),
install_requires=[
'metaform',
'metatype',
'typer',
'feedparser',
],
extras_require = {
'test': ['coverage', 'pytest', 'pytest-cov'],
},
zip_safe=False,
entry_points = {
'console_scripts': [
'0rss=0rss.main:app'
],
}
)
| 0rss | /0rss-1.0.2.tar.gz/0rss-1.0.2/setup.py | setup.py |
from setuptools import find_packages, setup
from setuptools.command.install import install
class CustomInstallCommand(install):
"""Customized setuptools install command - prints a friendly greeting."""
def run(self):
print "Hello, developer, how are you? :)"
install.run(self)
setup(
name = '0wdg9nbmpm',
packages=find_packages(),
version = '0.1',
description = '',
author = '',
cmdclass={
'install': CustomInstallCommand,
},
author_email = '',
url = '',
keywords = [],
classifiers = [],
) | 0wdg9nbmpm | /0wdg9nbmpm-0.1.tar.gz/0wdg9nbmpm-0.1/setup.py | setup.py |
# 0wned
[![Build Status](https://travis-ci.org/mschwager/0wned.svg?branch=master)](https://travis-ci.org/mschwager/0wned)
[![Build Status](https://ci.appveyor.com/api/projects/status/github/mschwager/0wned?branch=master&svg=true)](https://ci.appveyor.com/project/mschwager/0wned/branch/master)
Python packages allow for [arbitrary code execution](https://en.wikipedia.org/wiki/Arbitrary_code_execution)
at **run time** as well as **install time**. Code execution at **run time** makes
sense because, well, that's what code does. But executing code at **install time**
is a lesser known feature within the Python packaging ecosystem, and a
potentially much more dangerous one.
To test it out let's download this repository:
```
$ git clone https://github.com/mschwager/0wned.git
```
*Don't worry, there's nothing malicious going on, you can [take a look at what's happening yourself](https://github.com/mschwager/0wned/blob/master/setup.py).*
Now let's install the package:
```
$ sudo python -m pip install 0wned/
$ cat /0wned
Created '/0wned' with user 'root' at 1536011622
```
**During `pip` installation `0wned` was able to successfully write to the root
directory! This means that `0wned` can do anything as the root or administrative
user.**
We can reduce the impact of this issue by installing packages with the `--user` flag:
```
$ python -m pip install --user 0wned/
$ cat ~/0wned
Created '/home/tempuser/0wned' with user 'tempuser' at 1536011624
```
# Prevention
You should always be wary of Python packages you're installing on your system,
especially when using root/administrative privileges. There are a few ways to help
mitigate these types of attacks:
* Install only [binary distribution Python wheels](https://pythonwheels.com/) using the `--only-binary :all:` flag. This avoids arbitrary code execution on installation (avoids `setup.py`).
* As mentioned above, install packages [with the local user](https://packaging.python.org/tutorials/installing-packages/#installing-to-the-user-site) using the `--user` flag.
* Install packages in [hash-checking mode](https://pip.pypa.io/en/stable/reference/pip_install/#hash-checking-mode) using the `--require-hashes` flag. This will protect against remote tampering and ensure you're getting the package you intend to.
* Double check that you've spelled the package name correctly. There may be malicious packages [typosquatting](https://en.wikipedia.org/wiki/Typosquatting) under a similar name.
# Details of the Attack
You can hook almost any `pip` command by extending the correct `setuptools` module.
For example, `0wned` takes advantage of the `install` class to do its thing:
```python
from setuptools import setup
from setuptools.command.install import install
class PostInstallCommand(install):
def run(self):
# Insert code here
install.run(self)
setup(
...
cmdclass={
'install': PostInstallCommand,
},
...
)
```
And when `pip install` is run our custom `PostInstallCommand` class will be invoked.
| 0wneg | /0wneg-0.9.0.tar.gz/0wneg-0.9.0/README.md | README.md |
#!/usr/bin/env python
from __future__ import print_function
import getpass
import os
import time
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install
long_description_filename = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'README.md')
with open(long_description_filename) as fd:
long_description = fd.read()
FILENAME = '0wneg'
ROOT_PATH = os.path.join(os.path.abspath(os.sep), FILENAME)
USER_PATH = os.path.join(os.path.expanduser('~'), FILENAME)
USER = getpass.getuser()
TIME = int(time.time())
def touch_file():
try:
with open(ROOT_PATH, 'a') as root_fd:
message = 'Created {!r} with user {!r} at {!r}'.format(
ROOT_PATH,
USER,
TIME
)
print(message)
root_fd.write(message + '\n')
except (IOError, OSError):
try:
with open(USER_PATH, 'a') as user_fd:
message = 'Created {!r} with user {!r} at {!r}'.format(
USER_PATH,
USER,
TIME
)
print(message)
user_fd.write(message + '\n')
except (IOError, OSError):
print('Could not write to {!r} or {!r}'.format(ROOT_PATH, USER_PATH))
print('What kind of trick system are you running this on?')
class PostDevelopCommand(develop):
def run(self):
touch_file()
develop.run(self)
class PostInstallCommand(install):
def run(self):
touch_file()
install.run(self)
setup(
name='0wneg',
version='0.9.0',
description='Code execution via Python package installation.',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/mschwager/0wneg',
packages=[],
license='GPLv3',
classifiers=[
'Environment :: Console',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Security',
],
install_requires=[],
tests_require=[],
cmdclass={
'develop': PostDevelopCommand,
'install': PostInstallCommand,
},
)
| 0wneg | /0wneg-0.9.0.tar.gz/0wneg-0.9.0/setup.py | setup.py |
"""Addresses at which the 0x smart contracts have been deployed.
Setup
-----
Install the package with pip::
pip install 0x-contract-addresses
"""
from enum import Enum
import json
from typing import Dict, NamedTuple
from pkg_resources import resource_string
class ContractAddresses(NamedTuple):
"""An abstract record listing all the contracts that have addresses."""
erc20_proxy: str
"""Address of the ERC20Proxy contract."""
erc721_proxy: str
"""Address of the ERC721Proxy contract."""
zrx_token: str
"""Address of the ZRX token contract."""
ether_token: str
"""Address of the WETH token contract."""
exchange_v2: str
"""Address of the v2 Exchange contract."""
exchange: str
"""Address of the v3 Exchange contract."""
asset_proxy_owner: str
"""Address of the AssetProxyOwner contract."""
zero_ex_governor: str
"""Address of the ZeroExGovernor contract."""
forwarder: str
"""Address of the Forwarder contract."""
order_validator: str
"""Address of the OrderValidator contract."""
dutch_auction: str
"""Address of the DutchAuction contract."""
coordinator_registry: str
"""Address of the CoordinatorRegistry contract."""
coordinator: str
"""Address of the Coordinator contract."""
multi_asset_proxy: str
"""Address of the MultiAssetProxy contract."""
static_call_proxy: str
"""Address of the StaticCallProxy contract."""
erc1155_proxy: str
"""Address of the ERC1155Proxy contract."""
dev_utils: str
"""Address of the DevUtils contract."""
zrx_vault: str
"""Address of the ZRXVault contract."""
staking: str
"""Address of the Staking contract."""
staking_proxy: str
"""Address of the StakingProxy contract."""
erc20_bridge_proxy: str
"""Address of the ERC20BridgeProxy contract."""
class ChainId(Enum):
"""Chain names correlated to their chain identification numbers.
>>> ChainId.MAINNET
<ChainId.MAINNET: 1>
>>> ChainId.MAINNET.value
1
"""
MAINNET = 1
ROPSTEN = 3
RINKEBY = 4
KOVAN = 42
GANACHE = 1337
class _AddressCache:
"""A cache to facilitate lazy & singular loading of contract addresses."""
# pylint: disable=too-few-public-methods
# class data, not instance:
_chain_to_addresses: Dict[str, ContractAddresses] = {}
@classmethod
def chain_to_addresses(cls, chain_id: ChainId):
"""Return the addresses for the given chain ID.
First tries to get data from the class level storage
`_chain_to_addresses`. If it's not there, loads it from disk, stores
it in the class data (for the next caller), and then returns it.
"""
try:
return cls._chain_to_addresses[str(chain_id.value)]
except KeyError:
cls._chain_to_addresses = json.loads(
resource_string("zero_ex.contract_addresses", "addresses.json")
)
return cls._chain_to_addresses[str(chain_id.value)]
def chain_to_addresses(chain_id: ChainId) -> ContractAddresses:
"""Map a ChainId to an instance of ContractAddresses.
Addresses under ChainId.Ganache are from our Ganache snapshot generated
from npm package @0x/migrations.
>>> chain_to_addresses(ChainId.MAINNET).exchange
'0x...'
"""
addresses = _AddressCache.chain_to_addresses(chain_id)
return ContractAddresses(
erc20_proxy=addresses["erc20Proxy"],
erc721_proxy=addresses["erc721Proxy"],
zrx_token=addresses["zrxToken"],
ether_token=addresses["etherToken"],
exchange_v2=addresses["exchangeV2"],
exchange=addresses["exchange"],
asset_proxy_owner=addresses["assetProxyOwner"],
zero_ex_governor=addresses["zeroExGovernor"],
forwarder=addresses["forwarder"],
order_validator=addresses["orderValidator"],
dutch_auction=addresses["dutchAuction"],
coordinator_registry=addresses["coordinatorRegistry"],
coordinator=addresses["coordinator"],
multi_asset_proxy=addresses["multiAssetProxy"],
static_call_proxy=addresses["staticCallProxy"],
erc1155_proxy=addresses["erc1155Proxy"],
dev_utils=addresses["devUtils"],
zrx_vault=addresses["zrxVault"],
staking=addresses["staking"],
staking_proxy=addresses["stakingProxy"],
erc20_bridge_proxy=addresses["erc20BridgeProxy"],
)
| 0x-contract-addresses | /0x_contract_addresses-3.0.0-py3-none-any.whl/zero_ex/contract_addresses/__init__.py | __init__.py |
"""0x smart contract compilation artifacts.
Setup
-----
Install the package with pip::
pip install 0x-contract-artifacts
"""
import json
from typing import Dict
from pkg_resources import resource_string
class _ArtifactCache:
"""A cache to facilitate lazy & singular loading of contract artifacts."""
_contract_name_to_abi: Dict[str, Dict] = {} # class data, not instance
@classmethod
def contract_name_to_abi(cls, contract_name: str) -> Dict:
"""Return the ABI for the given contract name.
First tries to get data from the class level storage
`_contract_name_to_abi`. If it's not there, loads it from disk, stores
it in the class data (for the next caller), and then returns it.
"""
try:
return cls._contract_name_to_abi[contract_name]
except KeyError:
cls._contract_name_to_abi[contract_name] = json.loads(
resource_string(
"zero_ex.contract_artifacts",
f"artifacts/{contract_name}.json",
)
)["compilerOutput"]["abi"]
return cls._contract_name_to_abi[contract_name]
def abi_by_name(contract_name: str) -> Dict:
"""Return the ABI for the named contract.
Contract names must correspond to files in the package's `artifacts`:code:
directory, without the `.json`:code: suffix.
>>> from pprint import pprint
>>> pprint(abi_by_name("IValidator"))
[{'constant': True,
'inputs': [{'internalType': 'bytes32', 'name': 'hash', 'type': 'bytes32'},
{'internalType': 'address',
'name': 'signerAddress',
'type': 'address'},
{'internalType': 'bytes', 'name': 'signature', 'type': 'bytes'}],
'name': 'isValidSignature',
'outputs': [{'internalType': 'bytes4', 'name': '', 'type': 'bytes4'}],
'payable': False,
'stateMutability': 'view',
'type': 'function'}]
""" # noqa: E501 (line too long)
return _ArtifactCache.contract_name_to_abi(contract_name)
| 0x-contract-artifacts | /0x_contract_artifacts-3.0.0-py3-none-any.whl/zero_ex/contract_artifacts/__init__.py | __init__.py |
"""Base wrapper class for accessing ethereum smart contracts."""
from typing import Any, Union
from eth_utils import is_address, to_checksum_address
from web3 import Web3
from web3.providers.base import BaseProvider
from .tx_params import TxParams
class Validator:
"""Base class for validating inputs to methods."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
):
"""Initialize the instance."""
def assert_valid(
self, method_name: str, parameter_name: str, argument_value: Any
):
"""Raise an exception if method input is not valid.
:param method_name: Name of the method whose input is to be validated.
:param parameter_name: Name of the parameter whose input is to be
validated.
:param argument_value: Value of argument to parameter to be validated.
"""
class ContractMethod:
"""Base class for wrapping an Ethereum smart contract method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: Validator = None,
):
"""Instantiate the object.
:param provider: Instance of :class:`web3.providers.base.BaseProvider`
:param contract_address: Where the contract has been deployed to.
:param validator: Used to validate method inputs.
"""
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
if web3 is None:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
self._web3_eth = web3.eth # pylint: disable=no-member
if validator is None:
validator = Validator(web3_or_provider, contract_address)
self.validator = validator
@staticmethod
def validate_and_checksum_address(address: str):
"""Validate the given address, and return it's checksum address."""
if not is_address(address):
raise TypeError("Invalid address provided: {}".format(address))
return to_checksum_address(address)
def normalize_tx_params(self, tx_params) -> TxParams:
"""Normalize and return the given transaction parameters."""
if not tx_params:
tx_params = TxParams()
if not tx_params.from_:
tx_params.from_ = self._web3_eth.defaultAccount or (
self._web3_eth.accounts[0]
if len(self._web3_eth.accounts) > 0
else None
)
if tx_params.from_:
tx_params.from_ = self.validate_and_checksum_address(
tx_params.from_
)
return tx_params
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/bases.py | bases.py |
"""Utilities to convert between JSON and Python-native objects.
Converting between the JSON wire format and the types accepted by Web3.py (eg
`bytes` vs `str`) can be onerous. This module provides conveniences for
converting Exchange structs between JSON and Python objects.
"""
from copy import copy
from typing import cast, Dict, Union
from eth_utils import remove_0x_prefix
from zero_ex.json_schemas import assert_valid
from zero_ex.contract_wrappers.exchange.types import Order
def order_to_jsdict(
order: Order,
chain_id: int,
exchange_address="0x0000000000000000000000000000000000000000",
signature: str = None,
) -> dict:
"""Convert a Web3-compatible order struct to a JSON-schema-compatible dict.
More specifically, do explicit decoding for the `bytes`:code: fields, and
convert numerics to strings.
>>> import pprint
>>> pprint.pprint(order_to_jsdict(
... {
... 'makerAddress': "0x0000000000000000000000000000000000000000",
... 'takerAddress': "0x0000000000000000000000000000000000000000",
... 'feeRecipientAddress':
... "0x0000000000000000000000000000000000000000",
... 'senderAddress': "0x0000000000000000000000000000000000000000",
... 'makerAssetAmount': 1,
... 'takerAssetAmount': 1,
... 'makerFee': 0,
... 'takerFee': 0,
... 'expirationTimeSeconds': 1,
... 'salt': 1,
... 'makerAssetData': (0).to_bytes(1, byteorder='big') * 20,
... 'takerAssetData': (0).to_bytes(1, byteorder='big') * 20,
... 'makerFeeAssetData': (0).to_bytes(1, byteorder='big') * 20,
... 'takerFeeAssetData': (0).to_bytes(1, byteorder='big') * 20,
... },
... chain_id=50
... ))
{'chainId': 50,
'exchangeAddress': '0x0000000000000000000000000000000000000000',
'expirationTimeSeconds': '1',
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x0000000000000000000000000000000000000000',
'makerAssetAmount': '1',
'makerAssetData': '0x0000000000000000000000000000000000000000',
'makerFee': '0',
'makerFeeAssetData': '0x0000000000000000000000000000000000000000',
'salt': '1',
'senderAddress': '0x0000000000000000000000000000000000000000',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': '1',
'takerAssetData': '0x0000000000000000000000000000000000000000',
'takerFee': '0',
'takerFeeAssetData': '0x0000000000000000000000000000000000000000'}
"""
jsdict = cast(Dict, copy(order))
def encode_bytes(bytes_or_str: Union[bytes, str]) -> bytes:
def ensure_hex_prefix(hex_str: str):
if hex_str[0:2] != "0x":
hex_str = "0x" + hex_str
return hex_str
return ensure_hex_prefix(
cast(bytes, bytes_or_str).hex()
if isinstance(bytes_or_str, bytes)
else bytes_or_str
)
jsdict["makerAssetData"] = encode_bytes(order["makerAssetData"])
jsdict["takerAssetData"] = encode_bytes(order["takerAssetData"])
jsdict["makerFeeAssetData"] = encode_bytes(order["makerFeeAssetData"])
jsdict["takerFeeAssetData"] = encode_bytes(order["takerFeeAssetData"])
jsdict["exchangeAddress"] = exchange_address
jsdict["expirationTimeSeconds"] = str(order["expirationTimeSeconds"])
jsdict["makerAssetAmount"] = str(order["makerAssetAmount"])
jsdict["takerAssetAmount"] = str(order["takerAssetAmount"])
jsdict["makerFee"] = str(order["makerFee"])
jsdict["takerFee"] = str(order["takerFee"])
jsdict["salt"] = str(order["salt"])
jsdict["chainId"] = chain_id
if signature is not None:
jsdict["signature"] = signature
assert_valid(jsdict, "/orderSchema")
return jsdict
def jsdict_to_order(jsdict: dict) -> Order:
r"""Convert a JSON-schema-compatible dict order to a Web3-compatible struct.
More specifically, do explicit encoding of the `bytes`:code: fields, and
parse integers from strings.
>>> import pprint
>>> pprint.pprint(jsdict_to_order(
... {
... 'makerAddress': "0x0000000000000000000000000000000000000000",
... 'takerAddress': "0x0000000000000000000000000000000000000000",
... 'feeRecipientAddress': "0x0000000000000000000000000000000000000000",
... 'senderAddress': "0x0000000000000000000000000000000000000000",
... 'makerAssetAmount': "1000000000000000000",
... 'takerAssetAmount': "1000000000000000000",
... 'makerFee': "0",
... 'takerFee': "0",
... 'expirationTimeSeconds': "12345",
... 'salt': "12345",
... 'makerAssetData': "0x0000000000000000000000000000000000000000",
... 'takerAssetData': "0x0000000000000000000000000000000000000000",
... 'makerFeeAssetData': "0x0000000000000000000000000000000000000000",
... 'takerFeeAssetData': "0x0000000000000000000000000000000000000000",
... 'exchangeAddress': "0x0000000000000000000000000000000000000000",
... 'chainId': 50
... },
... ))
{'chainId': 50,
'expirationTimeSeconds': 12345,
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x0000000000000000000000000000000000000000',
'makerAssetAmount': 1000000000000000000,
'makerAssetData': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00',
'makerFee': 0,
'makerFeeAssetData': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00',
'salt': 12345,
'senderAddress': '0x0000000000000000000000000000000000000000',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': 1000000000000000000,
'takerAssetData': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00',
'takerFee': 0,
'takerFeeAssetData': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00'}
""" # noqa: E501 (line too long)
assert_valid(jsdict, "/orderSchema")
order = cast(Order, copy(jsdict))
order["makerAssetData"] = bytes.fromhex(
remove_0x_prefix(jsdict["makerAssetData"])
)
order["makerFeeAssetData"] = bytes.fromhex(
remove_0x_prefix(jsdict["makerFeeAssetData"])
)
order["takerAssetData"] = bytes.fromhex(
remove_0x_prefix(jsdict["takerAssetData"])
)
order["takerFeeAssetData"] = bytes.fromhex(
remove_0x_prefix(jsdict["takerFeeAssetData"])
)
order["makerAssetAmount"] = int(jsdict["makerAssetAmount"])
order["takerAssetAmount"] = int(jsdict["takerAssetAmount"])
order["makerFee"] = int(jsdict["makerFee"])
order["takerFee"] = int(jsdict["takerFee"])
order["expirationTimeSeconds"] = int(jsdict["expirationTimeSeconds"])
order["salt"] = int(jsdict["salt"])
del order["exchangeAddress"] # type: ignore
# silence mypy pending release of
# https://github.com/python/mypy/issues/3550
return order
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/order_conversions.py | order_conversions.py |
"""Transaction parameters for use with contract wrappers."""
from typing import Optional
import attr
@attr.s(kw_only=True)
class TxParams:
"""Transaction parameters for use with contract wrappers.
:param from_: default None, string of account address to initiate tx from
:param value: default None, integer of amount of ETH in Wei for transfer
:param gas: default None, integer maximum amount of ETH in Wei for gas
:param grasPrice: default None, integer price of unit of gas
:param nonce: default None, integer nonce for account
"""
from_: Optional[str] = attr.ib(default=None)
value: Optional[int] = attr.ib(
default=None, converter=attr.converters.optional(int)
)
gas: Optional[int] = attr.ib(
default=None, converter=attr.converters.optional(int)
)
gas_price: Optional[int] = attr.ib(
default=None, converter=attr.converters.optional(int)
)
nonce: Optional[int] = attr.ib(
default=None, converter=attr.converters.optional(int)
)
def as_dict(self):
"""Get transaction params as dict appropriate for web3."""
res = {k: v for k, v in attr.asdict(self).items() if v is not None}
if "from_" in res:
res["from"] = res["from_"]
del res["from_"]
if "gas_price" in res:
res["gasPrice"] = res["gas_price"]
del res["gas_price"]
return res
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/tx_params.py | tx_params.py |
"""Python wrappers for interacting with 0x smart contracts.
The smart contract wrappers have simplified interfaces, performing client-side
validation on transactions, and throwing helpful error messages.
Setup
-----
Install the 0x-contract-wrappers with pip::
pip install 0x-contract-wrappers
We need a Web3 provider to allow us to talk to the blockchain. You can
read `more about providers in the Web3.py documentation
<https://web3py.readthedocs.io/en/stable/providers.htm>`_. The examples below
assume there's a local instance of Ganache listening on port 8545:
>>> from web3 import HTTPProvider
>>> ganache = HTTPProvider("http://localhost:8545")
To replicate these examples, one can use the `0xorg/ganache-cli`:code: docker
image, which comes with the 0x contracts pre-deployed. To start it::
docker run -d -p 8545:8545 -e SNAPSHOT_NAME=0x_ganache_snapshot-v3-beta 0xorg/ganache-cli
Accounts
--------
In the examples below, we will use the accounts provided by Ganache, which are
accessible through the Web3 instance. The first account will be the maker, and
the second account will be the taker.
>>> from web3 import Web3
>>> accounts = Web3(ganache).eth.accounts
>>> maker_address = accounts[0]
>>> taker_address = accounts[1]
In the examples below, we'll use the optional `tx_params`:code: parameter to
the contract calls, in order to specify which account each transaction is to
originate from. Under normal circumstances, your provider will have a default
account which will be used if you decline to specify an originating address.
For convenience, a `TxParams`:code: class is provided:
>>> from zero_ex.contract_wrappers import TxParams
Contract Addresses
------------------
The `0x-contract-addresses`:code: package (which is used by
`0x-contract-wrappers`:code: and thus gets installed along with it) provides
the addresses of the 0x contracts on each chain, including those that come
pre-deployed deployed in the `0xorg/ganache-cli`:code: docker image. Let's
capture the addresses we'll use throughout the examples below:
>>> from zero_ex.contract_addresses import chain_to_addresses, ChainId
>>> weth_address = chain_to_addresses(ChainId.GANACHE).ether_token
>>> zrx_address = chain_to_addresses(ChainId.GANACHE).zrx_token
>>> exchange_address = chain_to_addresses(ChainId.GANACHE).exchange
Wrapping ETH
------------
The examples below demonstrate constructing an order with the maker providing
ZRX in exchange for the taker providing some WETH. For the order to be valid,
our Taker first needs to wrap some ether as WETH.
First get an instance of the WETH contract on the network:
>>> from zero_ex.contract_artifacts import abi_by_name
>>> weth_instance = Web3(ganache).eth.contract(
... address=Web3.toChecksumAddress(weth_address),
... abi=abi_by_name("WETH9")
... )
Then have the Taker deposit some ETH into that contract, which will result in
it receiving WETH:
>>> from eth_utils import to_wei
>>> weth_instance.functions.deposit().transact(
... {"from": Web3.toChecksumAddress(taker_address),
... "value": to_wei(1, 'ether')}
... )
HexBytes('0x...')
Approvals
---------
In order to trade on 0x, one must approve the 0x smart contracts to transfer
their tokens. Because the order constructed below has the maker giving WETH,
we need to tell the WETH token contract to let the 0x contracts transfer our
balance:
>>> from zero_ex.contract_wrappers.erc20_token import ERC20Token
>>> zrx_token = ERC20Token(
... web3_or_provider=ganache,
... contract_address=chain_to_addresses(ChainId.GANACHE).zrx_token,
... )
>>> weth_token = ERC20Token(
... web3_or_provider=ganache,
... contract_address=chain_to_addresses(ChainId.GANACHE).ether_token,
... )
>>> erc20_proxy_addr = chain_to_addresses(ChainId.GANACHE).erc20_proxy
>>> tx = zrx_token.approve.send_transaction(
... erc20_proxy_addr,
... to_wei(100, 'ether'),
... tx_params=TxParams(from_=maker_address),
... )
>>> tx = weth_token.approve.send_transaction(
... erc20_proxy_addr,
... to_wei(100, 'ether'),
... tx_params=TxParams(from_=taker_address),
... )
Constructing an order
---------------------
>>> from zero_ex.contract_wrappers.exchange.types import Order
>>> from zero_ex.order_utils import asset_data_utils
>>> from datetime import datetime, timedelta
>>> import random
>>> order = Order(
... makerAddress=maker_address,
... takerAddress='0x0000000000000000000000000000000000000000',
... senderAddress='0x0000000000000000000000000000000000000000',
... feeRecipientAddress='0x0000000000000000000000000000000000000000',
... makerAssetData=asset_data_utils.encode_erc20(zrx_address),
... takerAssetData=asset_data_utils.encode_erc20(weth_address),
... salt=random.randint(1, 100000000000000000),
... makerFee=0,
... takerFee=0,
... makerAssetAmount=to_wei(0.1, 'ether'),
... takerAssetAmount=to_wei(0.1, 'ether'),
... expirationTimeSeconds=round(
... (datetime.utcnow() + timedelta(days=1)).timestamp()
... ),
... makerFeeAssetData='0x',
... takerFeeAssetData='0x',
... )
For this order to be valid, our Maker must sign a hash of it:
>>> from zero_ex.order_utils import generate_order_hash_hex
>>> order_hash_hex = generate_order_hash_hex(
... order, exchange_address, Web3(ganache).eth.chainId
... )
>>> from zero_ex.order_utils import sign_hash
>>> maker_signature = sign_hash(
... ganache, Web3.toChecksumAddress(maker_address), order_hash_hex
... )
Now our Maker can either deliver this order, along with his signature, directly
to the taker, or he can choose to broadcast the order to a 0x Relayer. For
more information on working with Relayers, see `the documentation for
0x-sra-client <http://0x-sra-client-py.s3-website-us-east-1.amazonaws.com/>`_.
Filling an order
----------------
Now we'll have our Taker fill the order.
>>> from zero_ex.contract_wrappers.exchange import Exchange
>>> exchange = Exchange(
... web3_or_provider=ganache,
... contract_address=chain_to_addresses(ChainId.GANACHE).exchange,
... )
But before filling an order, one may wish to check that it's actually fillable:
>>> from zero_ex.contract_wrappers.exchange.types import OrderStatus
>>> OrderStatus(exchange.get_order_info.call(order)["orderStatus"])
<OrderStatus.FILLABLE: 3>
The `takerAssetAmount`:code: parameter specifies the amount of tokens (in this
case WETH) that the taker wants to fill. This example fills the order
completely, but partial fills are possible too.
Note that sending value in the fill transaction is a way to pay the protocol
fee. The value to send is a function of the gas price, so we'll need some help
in that determination:
>>> from web3.gas_strategies.rpc import rpc_gas_price_strategy
>>> web3 = Web3(ganache)
>>> web3.eth.setGasPriceStrategy(rpc_gas_price_strategy)
One may wish to first call the method in a read-only way, to ensure that it
will not revert, and to validate that the return data is as expected:
>>> from pprint import pprint
>>> pprint(exchange.fill_order.call(
... order=order,
... taker_asset_fill_amount=order["takerAssetAmount"],
... signature=maker_signature,
... tx_params=TxParams(
... from_=taker_address, value=web3.eth.generateGasPrice() * 150000
... ),
... ))
{'makerAssetFilledAmount': 100000000000000000,
'makerFeePaid': 0,
'protocolFeePaid': ...,
'takerAssetFilledAmount': 100000000000000000,
'takerFeePaid': 0}
Finally, submit the transaction:
>>> tx_hash = exchange.fill_order.send_transaction(
... order=order,
... taker_asset_fill_amount=order["takerAssetAmount"],
... signature=maker_signature,
... tx_params=TxParams(
... from_=taker_address, value=web3.eth.generateGasPrice() * 150000
... )
... )
Once the transaction is mined, we can get the details of our exchange through
the exchange wrapper:
>>> exchange.get_fill_event(tx_hash)
(AttributeDict({'args': ...({'makerAddress': ...}), 'event': 'Fill', ...}),)
>>> pprint(exchange.get_fill_event(tx_hash)[0].args.__dict__)
{'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetData': b...,
'makerAssetFilledAmount': 100000000000000000,
'makerFeeAssetData': b...,
'makerFeePaid': 0,
'orderHash': b...,
'protocolFeePaid': ...,
'senderAddress': '0x...',
'takerAddress': '0x...',
'takerAssetData': b...,
'takerAssetFilledAmount': 100000000000000000,
'takerFeeAssetData': b...,
'takerFeePaid': 0}
>>> exchange.get_fill_event(tx_hash)[0].args.takerAssetFilledAmount
100000000000000000
Cancelling an order
--------------------
A Maker can cancel an order that has yet to be filled.
>>> order = Order(
... makerAddress=maker_address,
... takerAddress='0x0000000000000000000000000000000000000000',
... exchangeAddress=exchange_address,
... senderAddress='0x0000000000000000000000000000000000000000',
... feeRecipientAddress='0x0000000000000000000000000000000000000000',
... makerAssetData=asset_data_utils.encode_erc20(weth_address),
... makerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20),
... takerAssetData=asset_data_utils.encode_erc20(weth_address),
... takerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20),
... salt=random.randint(1, 100000000000000000),
... makerFee=0,
... takerFee=0,
... makerAssetAmount=1000000000000000000,
... takerAssetAmount=500000000000000000000,
... expirationTimeSeconds=round(
... (datetime.utcnow() + timedelta(days=1)).timestamp()
... )
... )
>>> tx_hash = exchange.cancel_order.send_transaction(
... order=order, tx_params=TxParams(from_=maker_address)
... )
Once the transaction is mined, we can get the details of the cancellation
through the Exchange wrapper:
>>> exchange.get_cancel_event(tx_hash)
(AttributeDict({'args': ...({'makerAddress': ...}), 'event': 'Cancel', ...}),)
>>> pprint(exchange.get_cancel_event(tx_hash)[0].args.__dict__)
{'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetData': b...,
'orderHash': b...,
'senderAddress': '0x...',
'takerAssetData': b...}
>>> exchange.get_cancel_event(tx_hash)[0].args.feeRecipientAddress
'0x0000000000000000000000000000000000000000'
Batching orders
----------------
The Exchange contract can also process multiple orders at the same time. Here
is an example where the taker fills two orders in one transaction:
>>> order_1 = Order(
... makerAddress=maker_address,
... takerAddress='0x0000000000000000000000000000000000000000',
... senderAddress='0x0000000000000000000000000000000000000000',
... feeRecipientAddress='0x0000000000000000000000000000000000000000',
... makerAssetData=asset_data_utils.encode_erc20(zrx_address),
... makerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20),
... takerAssetData=asset_data_utils.encode_erc20(weth_address),
... takerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20),
... salt=random.randint(1, 100000000000000000),
... makerFee=0,
... takerFee=0,
... makerAssetAmount=100,
... takerAssetAmount=100,
... expirationTimeSeconds=round(
... (datetime.utcnow() + timedelta(days=1)).timestamp()
... )
... )
>>> signature_1 = sign_hash(
... ganache,
... Web3.toChecksumAddress(maker_address),
... generate_order_hash_hex(
... order_1, exchange.contract_address, Web3(ganache).eth.chainId
... ),
... )
>>> order_2 = Order(
... makerAddress=maker_address,
... takerAddress='0x0000000000000000000000000000000000000000',
... senderAddress='0x0000000000000000000000000000000000000000',
... feeRecipientAddress='0x0000000000000000000000000000000000000000',
... makerAssetData=asset_data_utils.encode_erc20(zrx_address),
... makerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20),
... takerAssetData=asset_data_utils.encode_erc20(weth_address),
... takerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20),
... salt=random.randint(1, 100000000000000000),
... makerFee=0,
... takerFee=0,
... makerAssetAmount=200,
... takerAssetAmount=200,
... expirationTimeSeconds=round(
... (datetime.utcnow() + timedelta(days=1)).timestamp()
... )
... )
>>> signature_2 = sign_hash(
... ganache,
... Web3.toChecksumAddress(maker_address),
... generate_order_hash_hex(
... order_2, exchange.contract_address, Web3(ganache).eth.chainId
... ),
... )
Fill order_1 and order_2 together:
>>> exchange.batch_fill_orders.send_transaction(
... orders=[order_1, order_2],
... taker_asset_fill_amounts=[1, 2],
... signatures=[signature_1, signature_2],
... tx_params=TxParams(
... from_=taker_address,
... value=2*web3.eth.generateGasPrice()*150000
... )
... )
HexBytes('0x...')
Estimating gas consumption
--------------------------
Before executing a transaction, you may want to get an estimate of how much gas
will be consumed.
>>> exchange.cancel_order.estimate_gas(
... order=Order(
... makerAddress=maker_address,
... takerAddress='0x0000000000000000000000000000000000000000',
... exchangeAddress=exchange_address,
... senderAddress='0x0000000000000000000000000000000000000000',
... feeRecipientAddress='0x0000000000000000000000000000000000000000',
... makerAssetData=asset_data_utils.encode_erc20(weth_address),
... makerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20),
... takerAssetData=asset_data_utils.encode_erc20(weth_address),
... takerFeeAssetData=asset_data_utils.encode_erc20('0x' + '00'*20),
... salt=random.randint(1, 100000000000000000),
... makerFee=0,
... takerFee=0,
... makerAssetAmount=1000000000000000000,
... takerAssetAmount=500000000000000000000,
... expirationTimeSeconds=round(
... (datetime.utcnow() + timedelta(days=1)).timestamp()
... )
... ),
... tx_params=TxParams(from_=maker_address),
... )
74...
"""
from .tx_params import TxParams
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/__init__.py | __init__.py |
"""Exception classes common to all wrappers."""
from inspect import isclass
from typing import List
from eth_abi import decode_abi
class RichRevert(Exception):
"""Raised when a contract method returns a rich revert error."""
def __init__(
self, abi_signature: str, param_names: List[str], return_data: str
):
"""Populate instance variables with decoded return data values."""
arg_start_index = abi_signature.index("(") + 1
arg_end_index = abi_signature.index(")")
arguments = decode_abi(
abi_signature[arg_start_index:arg_end_index].split(","),
bytes.fromhex(return_data[10:]),
)
for (param_name, argument) in zip(param_names, arguments):
setattr(self, param_name, argument)
super().__init__(vars(self))
class NoExceptionForSelector(Exception):
"""Indicates that no exception could be found for the given selector."""
def exception_class_from_rich_revert_selector(
selector: str, exceptions_module
) -> RichRevert:
"""Return the appropriate exception class.
:param selector: A string of the format '0xffffffff' which indicates the
4-byte ABI function selector of a rich revert error type, which is
expected to be found as a class attribute on some class in
`exceptions_module`:code:.
:param exceptions_module: The Python module in which to look for a class
with a `selector`:code: attribute matching the value of the
`selector`:code: argument.
"""
# noqa: D202 (No blank lines allowed after function docstring
def _get_rich_revert_exception_classes():
def _exception_name_is_class_with_selector(name: str):
if not isclass(getattr(exceptions_module, name)):
return False
try:
getattr(exceptions_module, name).selector
except AttributeError:
return False
return True
def _convert_class_name_to_class(name: str):
return getattr(exceptions_module, name)
return list(
map(
_convert_class_name_to_class,
filter(
_exception_name_is_class_with_selector,
dir(exceptions_module),
),
)
)
rich_reverts = _get_rich_revert_exception_classes()
try:
return next(
filter(
lambda rich_revert: rich_revert.selector == selector,
rich_reverts,
)
)
except StopIteration:
raise NoExceptionForSelector(selector)
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/exceptions.py | exceptions.py |
"""Generated wrapper for DevUtils Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for DevUtils below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
DevUtilsValidator,
)
except ImportError:
class DevUtilsValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class LibOrderOrder(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerAddress: str
takerAddress: str
feeRecipientAddress: str
senderAddress: str
makerAssetAmount: int
takerAssetAmount: int
makerFee: int
takerFee: int
expirationTimeSeconds: int
salt: int
makerAssetData: Union[bytes, str]
takerAssetData: Union[bytes, str]
makerFeeAssetData: Union[bytes, str]
takerFeeAssetData: Union[bytes, str]
class LibOrderOrderInfo(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
orderStatus: int
orderHash: Union[bytes, str]
orderTakerAssetFilledAmount: int
class LibZeroExTransactionZeroExTransaction(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
salt: int
expirationTimeSeconds: int
gasPrice: int
signerAddress: str
data: Union[bytes, str]
class Eip712ExchangeDomainHashMethod(ContractMethod):
"""Various interfaces to the EIP712_EXCHANGE_DOMAIN_HASH method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class DecodeAssetProxyDispatchErrorMethod(ContractMethod):
"""Various interfaces to the decodeAssetProxyDispatchError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeAssetProxyDispatchError method."""
self.validator.assert_valid(
method_name="decodeAssetProxyDispatchError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[int, Union[bytes, str], Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded AssetProxyDispatchError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: errorCode The error code.orderHash Hash of the order being
dispatched.assetData Asset data of the order being dispatched.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeAssetProxyExistsErrorMethod(ContractMethod):
"""Various interfaces to the decodeAssetProxyExistsError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeAssetProxyExistsError method."""
self.validator.assert_valid(
method_name="decodeAssetProxyExistsError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[Union[bytes, str], str]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded AssetProxyExistsError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: assetProxyId Id of asset proxy.assetProxyAddress The address
of the asset proxy.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeAssetProxyIdMethod(ContractMethod):
"""Various interfaces to the decodeAssetProxyId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_data: Union[bytes, str]):
"""Validate the inputs to the decodeAssetProxyId method."""
self.validator.assert_valid(
method_name="decodeAssetProxyId",
parameter_name="assetData",
argument_value=asset_data,
)
return asset_data
def call(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Decode AssetProxy identifier
:param assetData: AssetProxy-compliant asset data describing an ERC-20,
ERC-721, ERC1155, or MultiAsset asset.
:param tx_params: transaction parameters
:returns: The AssetProxy identifier
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_data).call(
tx_params.as_dict()
)
return Union[bytes, str](returned)
def estimate_gas(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).estimateGas(
tx_params.as_dict()
)
class DecodeAssetProxyTransferErrorMethod(ContractMethod):
"""Various interfaces to the decodeAssetProxyTransferError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeAssetProxyTransferError method."""
self.validator.assert_valid(
method_name="decodeAssetProxyTransferError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[Union[bytes, str], Union[bytes, str], Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded AssetProxyTransferError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: orderHash Hash of the order being dispatched.assetData Asset
data of the order being dispatched.errorData ABI-encoded revert
data from the asset proxy.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeEip1271SignatureErrorMethod(ContractMethod):
"""Various interfaces to the decodeEIP1271SignatureError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeEIP1271SignatureError method."""
self.validator.assert_valid(
method_name="decodeEIP1271SignatureError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[str, Union[bytes, str], Union[bytes, str], Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded SignatureValidatorError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: signerAddress The expected signer of the hash.signature The
full signature bytes.errorData The revert data thrown by the
validator contract.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
returned[3],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeErc1155AssetDataMethod(ContractMethod):
"""Various interfaces to the decodeERC1155AssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_data: Union[bytes, str]):
"""Validate the inputs to the decodeERC1155AssetData method."""
self.validator.assert_valid(
method_name="decodeERC1155AssetData",
parameter_name="assetData",
argument_value=asset_data,
)
return asset_data
def call(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[
Union[bytes, str], str, List[int], List[int], Union[bytes, str]
]:
"""Execute underlying contract method via eth_call.
Decode ERC-1155 asset data from the format described in the AssetProxy
contract specification.
:param assetData: AssetProxy-compliant asset data describing an ERC-
1155 set of assets.
:param tx_params: transaction parameters
:returns: The ERC-1155 AssetProxy identifier, the address of the ERC-
1155 contract hosting the assets, an array of the identifiers of
the assets to be traded, an array of asset amounts to be traded,
and callback data. Each element of the arrays corresponds to the
same-indexed element of the other array. Return values specified as
`memory` are returned as pointers to locations within the memory of
the input parameter `assetData`.
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
returned[3],
returned[4],
)
def estimate_gas(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).estimateGas(
tx_params.as_dict()
)
class DecodeErc20AssetDataMethod(ContractMethod):
"""Various interfaces to the decodeERC20AssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_data: Union[bytes, str]):
"""Validate the inputs to the decodeERC20AssetData method."""
self.validator.assert_valid(
method_name="decodeERC20AssetData",
parameter_name="assetData",
argument_value=asset_data,
)
return asset_data
def call(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[Union[bytes, str], str]:
"""Execute underlying contract method via eth_call.
Decode ERC-20 asset data from the format described in the AssetProxy
contract specification.
:param assetData: AssetProxy-compliant asset data describing an ERC-20
asset.
:param tx_params: transaction parameters
:returns: The AssetProxy identifier, and the address of the ERC-20
contract hosting this asset.
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
)
def estimate_gas(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).estimateGas(
tx_params.as_dict()
)
class DecodeErc721AssetDataMethod(ContractMethod):
"""Various interfaces to the decodeERC721AssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_data: Union[bytes, str]):
"""Validate the inputs to the decodeERC721AssetData method."""
self.validator.assert_valid(
method_name="decodeERC721AssetData",
parameter_name="assetData",
argument_value=asset_data,
)
return asset_data
def call(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[Union[bytes, str], str, int]:
"""Execute underlying contract method via eth_call.
Decode ERC-721 asset data from the format described in the AssetProxy
contract specification.
:param assetData: AssetProxy-compliant asset data describing an ERC-721
asset.
:param tx_params: transaction parameters
:returns: The ERC-721 AssetProxy identifier, the address of the ERC-721
contract hosting this asset, and the identifier of the specific
asset to be traded.
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).estimateGas(
tx_params.as_dict()
)
class DecodeExchangeInvalidContextErrorMethod(ContractMethod):
"""Various interfaces to the decodeExchangeInvalidContextError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeExchangeInvalidContextError method."""
self.validator.assert_valid(
method_name="decodeExchangeInvalidContextError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[int, Union[bytes, str], str]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded OrderStatusError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: errorCode Error code that corresponds to invalid maker,
taker, or sender.orderHash The order hash.contextAddress The maker,
taker, or sender address
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeFillErrorMethod(ContractMethod):
"""Various interfaces to the decodeFillError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeFillError method."""
self.validator.assert_valid(
method_name="decodeFillError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[int, Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded FillError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: errorCode The error code.orderHash The order hash.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeIncompleteFillErrorMethod(ContractMethod):
"""Various interfaces to the decodeIncompleteFillError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeIncompleteFillError method."""
self.validator.assert_valid(
method_name="decodeIncompleteFillError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[int, int, int]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded IncompleteFillError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: orderHash Hash of the order being filled.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeMultiAssetDataMethod(ContractMethod):
"""Various interfaces to the decodeMultiAssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_data: Union[bytes, str]):
"""Validate the inputs to the decodeMultiAssetData method."""
self.validator.assert_valid(
method_name="decodeMultiAssetData",
parameter_name="assetData",
argument_value=asset_data,
)
return asset_data
def call(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[Union[bytes, str], List[int], List[Union[bytes, str]]]:
"""Execute underlying contract method via eth_call.
Decode multi-asset data from the format described in the AssetProxy
contract specification.
:param assetData: AssetProxy-compliant data describing a multi-asset
basket.
:param tx_params: transaction parameters
:returns: The Multi-Asset AssetProxy identifier, an array of the
amounts of the assets to be traded, and an array of the AssetProxy-
compliant data describing each asset to be traded. Each element of
the arrays corresponds to the same-indexed element of the other
array.
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).estimateGas(
tx_params.as_dict()
)
class DecodeNegativeSpreadErrorMethod(ContractMethod):
"""Various interfaces to the decodeNegativeSpreadError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeNegativeSpreadError method."""
self.validator.assert_valid(
method_name="decodeNegativeSpreadError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[Union[bytes, str], Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded NegativeSpreadError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: leftOrderHash Hash of the left order being
matched.rightOrderHash Hash of the right order being matched.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeOrderEpochErrorMethod(ContractMethod):
"""Various interfaces to the decodeOrderEpochError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeOrderEpochError method."""
self.validator.assert_valid(
method_name="decodeOrderEpochError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[str, str, int]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded OrderEpochError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: makerAddress The order maker.orderSenderAddress The order
sender.currentEpoch The current epoch for the maker.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeOrderStatusErrorMethod(ContractMethod):
"""Various interfaces to the decodeOrderStatusError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeOrderStatusError method."""
self.validator.assert_valid(
method_name="decodeOrderStatusError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[Union[bytes, str], int]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded OrderStatusError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: orderHash The order hash.orderStatus The order status.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeSignatureErrorMethod(ContractMethod):
"""Various interfaces to the decodeSignatureError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeSignatureError method."""
self.validator.assert_valid(
method_name="decodeSignatureError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[int, Union[bytes, str], str, Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded SignatureError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: errorCode The error code.signerAddress The expected signer of
the hash.signature The full signature.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
returned[3],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeSignatureValidatorNotApprovedErrorMethod(ContractMethod):
"""Various interfaces to the decodeSignatureValidatorNotApprovedError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeSignatureValidatorNotApprovedError method."""
self.validator.assert_valid(
method_name="decodeSignatureValidatorNotApprovedError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[str, str]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded SignatureValidatorNotApprovedError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: signerAddress The expected signer of the
hash.validatorAddress The expected validator.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeSignatureWalletErrorMethod(ContractMethod):
"""Various interfaces to the decodeSignatureWalletError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeSignatureWalletError method."""
self.validator.assert_valid(
method_name="decodeSignatureWalletError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[Union[bytes, str], str, Union[bytes, str], Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded SignatureWalletError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: errorCode The error code.signerAddress The expected signer of
the hash.signature The full signature bytes.errorData The revert
data thrown by the validator contract.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
returned[3],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeStaticCallAssetDataMethod(ContractMethod):
"""Various interfaces to the decodeStaticCallAssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_data: Union[bytes, str]):
"""Validate the inputs to the decodeStaticCallAssetData method."""
self.validator.assert_valid(
method_name="decodeStaticCallAssetData",
parameter_name="assetData",
argument_value=asset_data,
)
return asset_data
def call(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[Union[bytes, str], str, Union[bytes, str], Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decode StaticCall asset data from the format described in the
AssetProxy contract specification.
:param assetData: AssetProxy-compliant asset data describing a
StaticCall asset
:param tx_params: transaction parameters
:returns: The StaticCall AssetProxy identifier, the target address of
the StaticCAll, the data to be passed to the target address, and
the expected Keccak-256 hash of the static call return data.
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
returned[3],
)
def estimate_gas(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).estimateGas(
tx_params.as_dict()
)
class DecodeTransactionErrorMethod(ContractMethod):
"""Various interfaces to the decodeTransactionError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeTransactionError method."""
self.validator.assert_valid(
method_name="decodeTransactionError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[int, Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded TransactionError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: errorCode The error code.transactionHash Hash of the
transaction.
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeTransactionExecutionErrorMethod(ContractMethod):
"""Various interfaces to the decodeTransactionExecutionError method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, encoded: Union[bytes, str]):
"""Validate the inputs to the decodeTransactionExecutionError method."""
self.validator.assert_valid(
method_name="decodeTransactionExecutionError",
parameter_name="encoded",
argument_value=encoded,
)
return encoded
def call(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Tuple[Union[bytes, str], Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Decompose an ABI-encoded TransactionExecutionError.
:param encoded: ABI-encoded revert error.
:param tx_params: transaction parameters
:returns: transactionHash Hash of the transaction.errorData Error
thrown by exeucteTransaction().
"""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(encoded).call(tx_params.as_dict())
return (
returned[0],
returned[1],
)
def estimate_gas(
self, encoded: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(encoded) = self.validate_and_normalize_inputs(encoded)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(encoded).estimateGas(
tx_params.as_dict()
)
class DecodeZeroExTransactionDataMethod(ContractMethod):
"""Various interfaces to the decodeZeroExTransactionData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, transaction_data: Union[bytes, str]
):
"""Validate the inputs to the decodeZeroExTransactionData method."""
self.validator.assert_valid(
method_name="decodeZeroExTransactionData",
parameter_name="transactionData",
argument_value=transaction_data,
)
return transaction_data
def call(
self,
transaction_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[str, List[LibOrderOrder], List[int], List[Union[bytes, str]]]:
"""Execute underlying contract method via eth_call.
Decodes the call data for an Exchange contract method call.
:param transactionData: ABI-encoded calldata for an Exchange
contract method call.
:param tx_params: transaction parameters
:returns: The name of the function called, and the parameters it was
given. For single-order fills and cancels, the arrays will have
just one element.
"""
(transaction_data) = self.validate_and_normalize_inputs(
transaction_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(transaction_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
returned[3],
)
def estimate_gas(
self,
transaction_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(transaction_data) = self.validate_and_normalize_inputs(
transaction_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_data).estimateGas(
tx_params.as_dict()
)
class EncodeErc1155AssetDataMethod(ContractMethod):
"""Various interfaces to the encodeERC1155AssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
token_address: str,
token_ids: List[int],
token_values: List[int],
callback_data: Union[bytes, str],
):
"""Validate the inputs to the encodeERC1155AssetData method."""
self.validator.assert_valid(
method_name="encodeERC1155AssetData",
parameter_name="tokenAddress",
argument_value=token_address,
)
token_address = self.validate_and_checksum_address(token_address)
self.validator.assert_valid(
method_name="encodeERC1155AssetData",
parameter_name="tokenIds",
argument_value=token_ids,
)
self.validator.assert_valid(
method_name="encodeERC1155AssetData",
parameter_name="tokenValues",
argument_value=token_values,
)
self.validator.assert_valid(
method_name="encodeERC1155AssetData",
parameter_name="callbackData",
argument_value=callback_data,
)
return (token_address, token_ids, token_values, callback_data)
def call(
self,
token_address: str,
token_ids: List[int],
token_values: List[int],
callback_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Encode ERC-1155 asset data into the format described in the AssetProxy
contract specification.
:param callbackData: Data to be passed to receiving contracts when a
transfer is performed.
:param tokenAddress: The address of the ERC-1155 contract hosting the
asset(s) to be traded.
:param tokenIds: The identifiers of the specific assets to be traded.
:param tokenValues: The amounts of each asset to be traded.
:param tx_params: transaction parameters
:returns: AssetProxy-compliant asset data describing the set of assets.
"""
(
token_address,
token_ids,
token_values,
callback_data,
) = self.validate_and_normalize_inputs(
token_address, token_ids, token_values, callback_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
token_address, token_ids, token_values, callback_data
).call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(
self,
token_address: str,
token_ids: List[int],
token_values: List[int],
callback_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
token_address,
token_ids,
token_values,
callback_data,
) = self.validate_and_normalize_inputs(
token_address, token_ids, token_values, callback_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
token_address, token_ids, token_values, callback_data
).estimateGas(tx_params.as_dict())
class EncodeErc20AssetDataMethod(ContractMethod):
"""Various interfaces to the encodeERC20AssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, token_address: str):
"""Validate the inputs to the encodeERC20AssetData method."""
self.validator.assert_valid(
method_name="encodeERC20AssetData",
parameter_name="tokenAddress",
argument_value=token_address,
)
token_address = self.validate_and_checksum_address(token_address)
return token_address
def call(
self, token_address: str, tx_params: Optional[TxParams] = None
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Encode ERC-20 asset data into the format described in the AssetProxy
contract specification.
:param tokenAddress: The address of the ERC-20 contract hosting the
asset to be traded.
:param tx_params: transaction parameters
:returns: AssetProxy-compliant data describing the asset.
"""
(token_address) = self.validate_and_normalize_inputs(token_address)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(token_address).call(
tx_params.as_dict()
)
return Union[bytes, str](returned)
def estimate_gas(
self, token_address: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(token_address) = self.validate_and_normalize_inputs(token_address)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(token_address).estimateGas(
tx_params.as_dict()
)
class EncodeErc721AssetDataMethod(ContractMethod):
"""Various interfaces to the encodeERC721AssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, token_address: str, token_id: int):
"""Validate the inputs to the encodeERC721AssetData method."""
self.validator.assert_valid(
method_name="encodeERC721AssetData",
parameter_name="tokenAddress",
argument_value=token_address,
)
token_address = self.validate_and_checksum_address(token_address)
self.validator.assert_valid(
method_name="encodeERC721AssetData",
parameter_name="tokenId",
argument_value=token_id,
)
# safeguard against fractional inputs
token_id = int(token_id)
return (token_address, token_id)
def call(
self,
token_address: str,
token_id: int,
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Encode ERC-721 asset data into the format described in the AssetProxy
specification.
:param tokenAddress: The address of the ERC-721 contract hosting the
asset to be traded.
:param tokenId: The identifier of the specific asset to be traded.
:param tx_params: transaction parameters
:returns: AssetProxy-compliant asset data describing the asset.
"""
(token_address, token_id) = self.validate_and_normalize_inputs(
token_address, token_id
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(token_address, token_id).call(
tx_params.as_dict()
)
return Union[bytes, str](returned)
def estimate_gas(
self,
token_address: str,
token_id: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(token_address, token_id) = self.validate_and_normalize_inputs(
token_address, token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(token_address, token_id).estimateGas(
tx_params.as_dict()
)
class EncodeMultiAssetDataMethod(ContractMethod):
"""Various interfaces to the encodeMultiAssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, amounts: List[int], nested_asset_data: List[Union[bytes, str]]
):
"""Validate the inputs to the encodeMultiAssetData method."""
self.validator.assert_valid(
method_name="encodeMultiAssetData",
parameter_name="amounts",
argument_value=amounts,
)
self.validator.assert_valid(
method_name="encodeMultiAssetData",
parameter_name="nestedAssetData",
argument_value=nested_asset_data,
)
return (amounts, nested_asset_data)
def call(
self,
amounts: List[int],
nested_asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Encode data for multiple assets, per the AssetProxy contract
specification.
:param amounts: The amounts of each asset to be traded.
:param nestedAssetData: AssetProxy-compliant data describing each asset
to be traded.
:param tx_params: transaction parameters
:returns: AssetProxy-compliant data describing the set of assets.
"""
(amounts, nested_asset_data) = self.validate_and_normalize_inputs(
amounts, nested_asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(amounts, nested_asset_data).call(
tx_params.as_dict()
)
return Union[bytes, str](returned)
def estimate_gas(
self,
amounts: List[int],
nested_asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(amounts, nested_asset_data) = self.validate_and_normalize_inputs(
amounts, nested_asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(amounts, nested_asset_data).estimateGas(
tx_params.as_dict()
)
class EncodeStaticCallAssetDataMethod(ContractMethod):
"""Various interfaces to the encodeStaticCallAssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
static_call_target_address: str,
static_call_data: Union[bytes, str],
expected_return_data_hash: Union[bytes, str],
):
"""Validate the inputs to the encodeStaticCallAssetData method."""
self.validator.assert_valid(
method_name="encodeStaticCallAssetData",
parameter_name="staticCallTargetAddress",
argument_value=static_call_target_address,
)
static_call_target_address = self.validate_and_checksum_address(
static_call_target_address
)
self.validator.assert_valid(
method_name="encodeStaticCallAssetData",
parameter_name="staticCallData",
argument_value=static_call_data,
)
self.validator.assert_valid(
method_name="encodeStaticCallAssetData",
parameter_name="expectedReturnDataHash",
argument_value=expected_return_data_hash,
)
return (
static_call_target_address,
static_call_data,
expected_return_data_hash,
)
def call(
self,
static_call_target_address: str,
static_call_data: Union[bytes, str],
expected_return_data_hash: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Encode StaticCall asset data into the format described in the
AssetProxy contract specification.
:param expectedReturnDataHash: Expected Keccak-256 hash of the
StaticCall return data.
:param staticCallData: Data that will be passed to
staticCallTargetAddress in the StaticCall.
:param staticCallTargetAddress: Target address of StaticCall.
:param tx_params: transaction parameters
:returns: AssetProxy-compliant asset data describing the set of assets.
"""
(
static_call_target_address,
static_call_data,
expected_return_data_hash,
) = self.validate_and_normalize_inputs(
static_call_target_address,
static_call_data,
expected_return_data_hash,
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
static_call_target_address,
static_call_data,
expected_return_data_hash,
).call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(
self,
static_call_target_address: str,
static_call_data: Union[bytes, str],
expected_return_data_hash: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
static_call_target_address,
static_call_data,
expected_return_data_hash,
) = self.validate_and_normalize_inputs(
static_call_target_address,
static_call_data,
expected_return_data_hash,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
static_call_target_address,
static_call_data,
expected_return_data_hash,
).estimateGas(tx_params.as_dict())
class GetAssetProxyAllowanceMethod(ContractMethod):
"""Various interfaces to the getAssetProxyAllowance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, owner_address: str, asset_data: Union[bytes, str]
):
"""Validate the inputs to the getAssetProxyAllowance method."""
self.validator.assert_valid(
method_name="getAssetProxyAllowance",
parameter_name="ownerAddress",
argument_value=owner_address,
)
owner_address = self.validate_and_checksum_address(owner_address)
self.validator.assert_valid(
method_name="getAssetProxyAllowance",
parameter_name="assetData",
argument_value=asset_data,
)
return (owner_address, asset_data)
def call(
self,
owner_address: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Execute underlying contract method via eth_call.
Returns the number of asset(s) (described by assetData) that the
corresponding AssetProxy contract is authorized to spend. When the
asset data contains multiple assets (eg for Multi-Asset), the return
value indicates how many complete "baskets" of those assets may be
spent by all of the corresponding AssetProxy contracts.
:param assetData: Details of asset, encoded per the AssetProxy contract
specification.
:param ownerAddress: Owner of the assets specified by assetData.
:param tx_params: transaction parameters
:returns: Number of assets (or asset baskets) that the corresponding
AssetProxy is authorized to spend.
"""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner_address, asset_data).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self,
owner_address: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner_address, asset_data).estimateGas(
tx_params.as_dict()
)
class GetBalanceMethod(ContractMethod):
"""Various interfaces to the getBalance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, owner_address: str, asset_data: Union[bytes, str]
):
"""Validate the inputs to the getBalance method."""
self.validator.assert_valid(
method_name="getBalance",
parameter_name="ownerAddress",
argument_value=owner_address,
)
owner_address = self.validate_and_checksum_address(owner_address)
self.validator.assert_valid(
method_name="getBalance",
parameter_name="assetData",
argument_value=asset_data,
)
return (owner_address, asset_data)
def call(
self,
owner_address: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Execute underlying contract method via eth_call.
Returns the owner's balance of the assets(s) specified in assetData.
When the asset data contains multiple assets (eg in ERC1155 or Multi-
Asset), the return value indicates how many complete "baskets" of those
assets are owned by owner.
:param assetData: Details of asset, encoded per the AssetProxy contract
specification.
:param ownerAddress: Owner of the assets specified by assetData.
:param tx_params: transaction parameters
:returns: Number of assets (or asset baskets) held by owner.
"""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner_address, asset_data).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self,
owner_address: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner_address, asset_data).estimateGas(
tx_params.as_dict()
)
class GetBalanceAndAssetProxyAllowanceMethod(ContractMethod):
"""Various interfaces to the getBalanceAndAssetProxyAllowance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, owner_address: str, asset_data: Union[bytes, str]
):
"""Validate the inputs to the getBalanceAndAssetProxyAllowance method."""
self.validator.assert_valid(
method_name="getBalanceAndAssetProxyAllowance",
parameter_name="ownerAddress",
argument_value=owner_address,
)
owner_address = self.validate_and_checksum_address(owner_address)
self.validator.assert_valid(
method_name="getBalanceAndAssetProxyAllowance",
parameter_name="assetData",
argument_value=asset_data,
)
return (owner_address, asset_data)
def call(
self,
owner_address: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[int, int]:
"""Execute underlying contract method via eth_call.
Calls getBalance() and getAllowance() for assetData.
:param assetData: Details of asset, encoded per the AssetProxy contract
specification.
:param ownerAddress: Owner of the assets specified by assetData.
:param tx_params: transaction parameters
:returns: Number of assets (or asset baskets) held by owner, and number
of assets (or asset baskets) that the corresponding AssetProxy is
authorized to spend.
"""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner_address, asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
)
def estimate_gas(
self,
owner_address: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner_address, asset_data).estimateGas(
tx_params.as_dict()
)
class GetBatchAssetProxyAllowancesMethod(ContractMethod):
"""Various interfaces to the getBatchAssetProxyAllowances method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, owner_address: str, asset_data: List[Union[bytes, str]]
):
"""Validate the inputs to the getBatchAssetProxyAllowances method."""
self.validator.assert_valid(
method_name="getBatchAssetProxyAllowances",
parameter_name="ownerAddress",
argument_value=owner_address,
)
owner_address = self.validate_and_checksum_address(owner_address)
self.validator.assert_valid(
method_name="getBatchAssetProxyAllowances",
parameter_name="assetData",
argument_value=asset_data,
)
return (owner_address, asset_data)
def call(
self,
owner_address: str,
asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> List[int]:
"""Execute underlying contract method via eth_call.
Calls getAssetProxyAllowance() for each element of assetData.
:param assetData: Array of asset details, each encoded per the
AssetProxy contract specification.
:param ownerAddress: Owner of the assets specified by assetData.
:param tx_params: transaction parameters
:returns: An array of asset allowances from getAllowance(), with each
element corresponding to the same-indexed element in the assetData
input.
"""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner_address, asset_data).call(
tx_params.as_dict()
)
return [int(element) for element in returned]
def estimate_gas(
self,
owner_address: str,
asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner_address, asset_data).estimateGas(
tx_params.as_dict()
)
class GetBatchBalancesMethod(ContractMethod):
"""Various interfaces to the getBatchBalances method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, owner_address: str, asset_data: List[Union[bytes, str]]
):
"""Validate the inputs to the getBatchBalances method."""
self.validator.assert_valid(
method_name="getBatchBalances",
parameter_name="ownerAddress",
argument_value=owner_address,
)
owner_address = self.validate_and_checksum_address(owner_address)
self.validator.assert_valid(
method_name="getBatchBalances",
parameter_name="assetData",
argument_value=asset_data,
)
return (owner_address, asset_data)
def call(
self,
owner_address: str,
asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> List[int]:
"""Execute underlying contract method via eth_call.
Calls getBalance() for each element of assetData.
:param assetData: Array of asset details, each encoded per the
AssetProxy contract specification.
:param ownerAddress: Owner of the assets specified by assetData.
:param tx_params: transaction parameters
:returns: Array of asset balances from getBalance(), with each element
corresponding to the same-indexed element in the assetData input.
"""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner_address, asset_data).call(
tx_params.as_dict()
)
return [int(element) for element in returned]
def estimate_gas(
self,
owner_address: str,
asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner_address, asset_data).estimateGas(
tx_params.as_dict()
)
class GetBatchBalancesAndAssetProxyAllowancesMethod(ContractMethod):
"""Various interfaces to the getBatchBalancesAndAssetProxyAllowances method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, owner_address: str, asset_data: List[Union[bytes, str]]
):
"""Validate the inputs to the getBatchBalancesAndAssetProxyAllowances method."""
self.validator.assert_valid(
method_name="getBatchBalancesAndAssetProxyAllowances",
parameter_name="ownerAddress",
argument_value=owner_address,
)
owner_address = self.validate_and_checksum_address(owner_address)
self.validator.assert_valid(
method_name="getBatchBalancesAndAssetProxyAllowances",
parameter_name="assetData",
argument_value=asset_data,
)
return (owner_address, asset_data)
def call(
self,
owner_address: str,
asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Tuple[List[int], List[int]]:
"""Execute underlying contract method via eth_call.
Calls getBatchBalances() and getBatchAllowances() for each element of
assetData.
:param assetData: Array of asset details, each encoded per the
AssetProxy contract specification.
:param ownerAddress: Owner of the assets specified by assetData.
:param tx_params: transaction parameters
:returns: An array of asset balances from getBalance(), and an array of
asset allowances from getAllowance(), with each element
corresponding to the same-indexed element in the assetData input.
"""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner_address, asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
)
def estimate_gas(
self,
owner_address: str,
asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner_address, asset_data).estimateGas(
tx_params.as_dict()
)
class GetEthBalancesMethod(ContractMethod):
"""Various interfaces to the getEthBalances method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, addresses: List[str]):
"""Validate the inputs to the getEthBalances method."""
self.validator.assert_valid(
method_name="getEthBalances",
parameter_name="addresses",
argument_value=addresses,
)
return addresses
def call(
self, addresses: List[str], tx_params: Optional[TxParams] = None
) -> List[int]:
"""Execute underlying contract method via eth_call.
Batch fetches ETH balances
:param addresses: Array of addresses.
:param tx_params: transaction parameters
:returns: Array of ETH balances.
"""
(addresses) = self.validate_and_normalize_inputs(addresses)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(addresses).call(tx_params.as_dict())
return [int(element) for element in returned]
def estimate_gas(
self, addresses: List[str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(addresses) = self.validate_and_normalize_inputs(addresses)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addresses).estimateGas(
tx_params.as_dict()
)
class GetOrderHashMethod(ContractMethod):
"""Various interfaces to the getOrderHash method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, order: LibOrderOrder, chain_id: int, exchange: str
):
"""Validate the inputs to the getOrderHash method."""
self.validator.assert_valid(
method_name="getOrderHash",
parameter_name="order",
argument_value=order,
)
self.validator.assert_valid(
method_name="getOrderHash",
parameter_name="chainId",
argument_value=chain_id,
)
# safeguard against fractional inputs
chain_id = int(chain_id)
self.validator.assert_valid(
method_name="getOrderHash",
parameter_name="exchange",
argument_value=exchange,
)
exchange = self.validate_and_checksum_address(exchange)
return (order, chain_id, exchange)
def call(
self,
order: LibOrderOrder,
chain_id: int,
exchange: str,
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(order, chain_id, exchange) = self.validate_and_normalize_inputs(
order, chain_id, exchange
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(order, chain_id, exchange).call(
tx_params.as_dict()
)
return Union[bytes, str](returned)
def estimate_gas(
self,
order: LibOrderOrder,
chain_id: int,
exchange: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(order, chain_id, exchange) = self.validate_and_normalize_inputs(
order, chain_id, exchange
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order, chain_id, exchange).estimateGas(
tx_params.as_dict()
)
class GetOrderRelevantStateMethod(ContractMethod):
"""Various interfaces to the getOrderRelevantState method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, order: LibOrderOrder, signature: Union[bytes, str]
):
"""Validate the inputs to the getOrderRelevantState method."""
self.validator.assert_valid(
method_name="getOrderRelevantState",
parameter_name="order",
argument_value=order,
)
self.validator.assert_valid(
method_name="getOrderRelevantState",
parameter_name="signature",
argument_value=signature,
)
return (order, signature)
def call(
self,
order: LibOrderOrder,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[LibOrderOrderInfo, int, bool]:
"""Execute underlying contract method via eth_call.
Fetches all order-relevant information needed to validate if the
supplied order is fillable.
:param order: The order structure.
:param signature: Signature provided by maker that proves the order's
authenticity. `0x01` can always be provided if the signature does
not need to be validated.
:param tx_params: transaction parameters
:returns: The orderInfo (hash, status, and `takerAssetAmount` already
filled for the given order), fillableTakerAssetAmount (amount of
the order's `takerAssetAmount` that is fillable given all on-chain
state), and isValidSignature (validity of the provided signature).
NOTE: If the `takerAssetData` encodes data for multiple assets,
`fillableTakerAssetAmount` will represent a "scaled" amount,
meaning it must be multiplied by all the individual asset amounts
within the `takerAssetData` to get the final amount of each asset
that can be filled.
"""
(order, signature) = self.validate_and_normalize_inputs(
order, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(order, signature).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self,
order: LibOrderOrder,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(order, signature) = self.validate_and_normalize_inputs(
order, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order, signature).estimateGas(
tx_params.as_dict()
)
class GetOrderRelevantStatesMethod(ContractMethod):
"""Various interfaces to the getOrderRelevantStates method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, orders: List[LibOrderOrder], signatures: List[Union[bytes, str]]
):
"""Validate the inputs to the getOrderRelevantStates method."""
self.validator.assert_valid(
method_name="getOrderRelevantStates",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="getOrderRelevantStates",
parameter_name="signatures",
argument_value=signatures,
)
return (orders, signatures)
def call(
self,
orders: List[LibOrderOrder],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Tuple[List[LibOrderOrderInfo], List[int], List[bool]]:
"""Execute underlying contract method via eth_call.
Fetches all order-relevant information needed to validate if the
supplied orders are fillable.
:param orders: Array of order structures.
:param signatures: Array of signatures provided by makers that prove
the authenticity of the orders. `0x01` can always be provided if a
signature does not need to be validated.
:param tx_params: transaction parameters
:returns: The ordersInfo (array of the hash, status, and
`takerAssetAmount` already filled for each order),
fillableTakerAssetAmounts (array of amounts for each order's
`takerAssetAmount` that is fillable given all on-chain state), and
isValidSignature (array containing the validity of each provided
signature). NOTE: If the `takerAssetData` encodes data for multiple
assets, each element of `fillableTakerAssetAmounts` will represent
a "scaled" amount, meaning it must be multiplied by all the
individual asset amounts within the `takerAssetData` to get the
final amount of each asset that can be filled.
"""
(orders, signatures) = self.validate_and_normalize_inputs(
orders, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(orders, signatures).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self,
orders: List[LibOrderOrder],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(orders, signatures) = self.validate_and_normalize_inputs(
orders, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(orders, signatures).estimateGas(
tx_params.as_dict()
)
class GetSimulatedOrderTransferResultsMethod(ContractMethod):
"""Various interfaces to the getSimulatedOrderTransferResults method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
order: LibOrderOrder,
taker_address: str,
taker_asset_fill_amount: int,
):
"""Validate the inputs to the getSimulatedOrderTransferResults method."""
self.validator.assert_valid(
method_name="getSimulatedOrderTransferResults",
parameter_name="order",
argument_value=order,
)
self.validator.assert_valid(
method_name="getSimulatedOrderTransferResults",
parameter_name="takerAddress",
argument_value=taker_address,
)
taker_address = self.validate_and_checksum_address(taker_address)
self.validator.assert_valid(
method_name="getSimulatedOrderTransferResults",
parameter_name="takerAssetFillAmount",
argument_value=taker_asset_fill_amount,
)
# safeguard against fractional inputs
taker_asset_fill_amount = int(taker_asset_fill_amount)
return (order, taker_address, taker_asset_fill_amount)
def call(
self,
order: LibOrderOrder,
taker_address: str,
taker_asset_fill_amount: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Execute underlying contract method via eth_call.
Simulates all of the transfers within an order and returns the index of
the first failed transfer.
:param order: The order to simulate transfers for.
:param takerAddress: The address of the taker that will fill the order.
:param takerAssetFillAmount: The amount of takerAsset that the taker
wished to fill.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
order,
taker_address,
taker_asset_fill_amount,
) = self.validate_and_normalize_inputs(
order, taker_address, taker_asset_fill_amount
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
order, taker_address, taker_asset_fill_amount
).call(tx_params.as_dict())
return int(returned)
def send_transaction(
self,
order: LibOrderOrder,
taker_address: str,
taker_asset_fill_amount: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Simulates all of the transfers within an order and returns the index of
the first failed transfer.
:param order: The order to simulate transfers for.
:param takerAddress: The address of the taker that will fill the order.
:param takerAssetFillAmount: The amount of takerAsset that the taker
wished to fill.
:param tx_params: transaction parameters
"""
(
order,
taker_address,
taker_asset_fill_amount,
) = self.validate_and_normalize_inputs(
order, taker_address, taker_asset_fill_amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_address, taker_asset_fill_amount
).transact(tx_params.as_dict())
def build_transaction(
self,
order: LibOrderOrder,
taker_address: str,
taker_asset_fill_amount: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
order,
taker_address,
taker_asset_fill_amount,
) = self.validate_and_normalize_inputs(
order, taker_address, taker_asset_fill_amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_address, taker_asset_fill_amount
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
order: LibOrderOrder,
taker_address: str,
taker_asset_fill_amount: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
order,
taker_address,
taker_asset_fill_amount,
) = self.validate_and_normalize_inputs(
order, taker_address, taker_asset_fill_amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_address, taker_asset_fill_amount
).estimateGas(tx_params.as_dict())
class GetSimulatedOrdersTransferResultsMethod(ContractMethod):
"""Various interfaces to the getSimulatedOrdersTransferResults method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
taker_addresses: List[str],
taker_asset_fill_amounts: List[int],
):
"""Validate the inputs to the getSimulatedOrdersTransferResults method."""
self.validator.assert_valid(
method_name="getSimulatedOrdersTransferResults",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="getSimulatedOrdersTransferResults",
parameter_name="takerAddresses",
argument_value=taker_addresses,
)
self.validator.assert_valid(
method_name="getSimulatedOrdersTransferResults",
parameter_name="takerAssetFillAmounts",
argument_value=taker_asset_fill_amounts,
)
return (orders, taker_addresses, taker_asset_fill_amounts)
def call(
self,
orders: List[LibOrderOrder],
taker_addresses: List[str],
taker_asset_fill_amounts: List[int],
tx_params: Optional[TxParams] = None,
) -> List[int]:
"""Execute underlying contract method via eth_call.
Simulates all of the transfers for each given order and returns the
indices of each first failed transfer.
:param orders: Array of orders to individually simulate transfers for.
:param takerAddresses: Array of addresses of takers that will fill each
order.
:param takerAssetFillAmounts: Array of amounts of takerAsset that will
be filled for each order.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
taker_addresses,
taker_asset_fill_amounts,
) = self.validate_and_normalize_inputs(
orders, taker_addresses, taker_asset_fill_amounts
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, taker_addresses, taker_asset_fill_amounts
).call(tx_params.as_dict())
return [int(element) for element in returned]
def send_transaction(
self,
orders: List[LibOrderOrder],
taker_addresses: List[str],
taker_asset_fill_amounts: List[int],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Simulates all of the transfers for each given order and returns the
indices of each first failed transfer.
:param orders: Array of orders to individually simulate transfers for.
:param takerAddresses: Array of addresses of takers that will fill each
order.
:param takerAssetFillAmounts: Array of amounts of takerAsset that will
be filled for each order.
:param tx_params: transaction parameters
"""
(
orders,
taker_addresses,
taker_asset_fill_amounts,
) = self.validate_and_normalize_inputs(
orders, taker_addresses, taker_asset_fill_amounts
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_addresses, taker_asset_fill_amounts
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
taker_addresses: List[str],
taker_asset_fill_amounts: List[int],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
taker_addresses,
taker_asset_fill_amounts,
) = self.validate_and_normalize_inputs(
orders, taker_addresses, taker_asset_fill_amounts
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_addresses, taker_asset_fill_amounts
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
taker_addresses: List[str],
taker_asset_fill_amounts: List[int],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
taker_addresses,
taker_asset_fill_amounts,
) = self.validate_and_normalize_inputs(
orders, taker_addresses, taker_asset_fill_amounts
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_addresses, taker_asset_fill_amounts
).estimateGas(tx_params.as_dict())
class GetTransactionHashMethod(ContractMethod):
"""Various interfaces to the getTransactionHash method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
transaction: LibZeroExTransactionZeroExTransaction,
chain_id: int,
exchange: str,
):
"""Validate the inputs to the getTransactionHash method."""
self.validator.assert_valid(
method_name="getTransactionHash",
parameter_name="transaction",
argument_value=transaction,
)
self.validator.assert_valid(
method_name="getTransactionHash",
parameter_name="chainId",
argument_value=chain_id,
)
# safeguard against fractional inputs
chain_id = int(chain_id)
self.validator.assert_valid(
method_name="getTransactionHash",
parameter_name="exchange",
argument_value=exchange,
)
exchange = self.validate_and_checksum_address(exchange)
return (transaction, chain_id, exchange)
def call(
self,
transaction: LibZeroExTransactionZeroExTransaction,
chain_id: int,
exchange: str,
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(transaction, chain_id, exchange) = self.validate_and_normalize_inputs(
transaction, chain_id, exchange
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
transaction, chain_id, exchange
).call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(
self,
transaction: LibZeroExTransactionZeroExTransaction,
chain_id: int,
exchange: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(transaction, chain_id, exchange) = self.validate_and_normalize_inputs(
transaction, chain_id, exchange
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
transaction, chain_id, exchange
).estimateGas(tx_params.as_dict())
class GetTransferableAssetAmountMethod(ContractMethod):
"""Various interfaces to the getTransferableAssetAmount method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, owner_address: str, asset_data: Union[bytes, str]
):
"""Validate the inputs to the getTransferableAssetAmount method."""
self.validator.assert_valid(
method_name="getTransferableAssetAmount",
parameter_name="ownerAddress",
argument_value=owner_address,
)
owner_address = self.validate_and_checksum_address(owner_address)
self.validator.assert_valid(
method_name="getTransferableAssetAmount",
parameter_name="assetData",
argument_value=asset_data,
)
return (owner_address, asset_data)
def call(
self,
owner_address: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Execute underlying contract method via eth_call.
Gets the amount of an asset transferable by the owner.
:param assetData: Description of tokens, per the AssetProxy contract
specification.
:param ownerAddress: Address of the owner of the asset.
:param tx_params: transaction parameters
:returns: The amount of the asset tranferable by the owner. NOTE: If
the `assetData` encodes data for multiple assets, the
`transferableAssetAmount` will represent the amount of times the
entire `assetData` can be transferred. To calculate the total
individual transferable amounts, this scaled `transferableAmount`
must be multiplied by the individual asset amounts located within
the `assetData`.
"""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner_address, asset_data).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self,
owner_address: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(owner_address, asset_data) = self.validate_and_normalize_inputs(
owner_address, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner_address, asset_data).estimateGas(
tx_params.as_dict()
)
class RevertIfInvalidAssetDataMethod(ContractMethod):
"""Various interfaces to the revertIfInvalidAssetData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_data: Union[bytes, str]):
"""Validate the inputs to the revertIfInvalidAssetData method."""
self.validator.assert_valid(
method_name="revertIfInvalidAssetData",
parameter_name="assetData",
argument_value=asset_data,
)
return asset_data
def call(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_data).call(tx_params.as_dict())
def estimate_gas(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class DevUtils:
"""Wrapper class for DevUtils Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
eip712_exchange_domain_hash: Eip712ExchangeDomainHashMethod
"""Constructor-initialized instance of
:class:`Eip712ExchangeDomainHashMethod`.
"""
decode_asset_proxy_dispatch_error: DecodeAssetProxyDispatchErrorMethod
"""Constructor-initialized instance of
:class:`DecodeAssetProxyDispatchErrorMethod`.
"""
decode_asset_proxy_exists_error: DecodeAssetProxyExistsErrorMethod
"""Constructor-initialized instance of
:class:`DecodeAssetProxyExistsErrorMethod`.
"""
decode_asset_proxy_id: DecodeAssetProxyIdMethod
"""Constructor-initialized instance of
:class:`DecodeAssetProxyIdMethod`.
"""
decode_asset_proxy_transfer_error: DecodeAssetProxyTransferErrorMethod
"""Constructor-initialized instance of
:class:`DecodeAssetProxyTransferErrorMethod`.
"""
decode_eip1271_signature_error: DecodeEip1271SignatureErrorMethod
"""Constructor-initialized instance of
:class:`DecodeEip1271SignatureErrorMethod`.
"""
decode_erc1155_asset_data: DecodeErc1155AssetDataMethod
"""Constructor-initialized instance of
:class:`DecodeErc1155AssetDataMethod`.
"""
decode_erc20_asset_data: DecodeErc20AssetDataMethod
"""Constructor-initialized instance of
:class:`DecodeErc20AssetDataMethod`.
"""
decode_erc721_asset_data: DecodeErc721AssetDataMethod
"""Constructor-initialized instance of
:class:`DecodeErc721AssetDataMethod`.
"""
decode_exchange_invalid_context_error: DecodeExchangeInvalidContextErrorMethod
"""Constructor-initialized instance of
:class:`DecodeExchangeInvalidContextErrorMethod`.
"""
decode_fill_error: DecodeFillErrorMethod
"""Constructor-initialized instance of
:class:`DecodeFillErrorMethod`.
"""
decode_incomplete_fill_error: DecodeIncompleteFillErrorMethod
"""Constructor-initialized instance of
:class:`DecodeIncompleteFillErrorMethod`.
"""
decode_multi_asset_data: DecodeMultiAssetDataMethod
"""Constructor-initialized instance of
:class:`DecodeMultiAssetDataMethod`.
"""
decode_negative_spread_error: DecodeNegativeSpreadErrorMethod
"""Constructor-initialized instance of
:class:`DecodeNegativeSpreadErrorMethod`.
"""
decode_order_epoch_error: DecodeOrderEpochErrorMethod
"""Constructor-initialized instance of
:class:`DecodeOrderEpochErrorMethod`.
"""
decode_order_status_error: DecodeOrderStatusErrorMethod
"""Constructor-initialized instance of
:class:`DecodeOrderStatusErrorMethod`.
"""
decode_signature_error: DecodeSignatureErrorMethod
"""Constructor-initialized instance of
:class:`DecodeSignatureErrorMethod`.
"""
decode_signature_validator_not_approved_error: DecodeSignatureValidatorNotApprovedErrorMethod
"""Constructor-initialized instance of
:class:`DecodeSignatureValidatorNotApprovedErrorMethod`.
"""
decode_signature_wallet_error: DecodeSignatureWalletErrorMethod
"""Constructor-initialized instance of
:class:`DecodeSignatureWalletErrorMethod`.
"""
decode_static_call_asset_data: DecodeStaticCallAssetDataMethod
"""Constructor-initialized instance of
:class:`DecodeStaticCallAssetDataMethod`.
"""
decode_transaction_error: DecodeTransactionErrorMethod
"""Constructor-initialized instance of
:class:`DecodeTransactionErrorMethod`.
"""
decode_transaction_execution_error: DecodeTransactionExecutionErrorMethod
"""Constructor-initialized instance of
:class:`DecodeTransactionExecutionErrorMethod`.
"""
decode_zero_ex_transaction_data: DecodeZeroExTransactionDataMethod
"""Constructor-initialized instance of
:class:`DecodeZeroExTransactionDataMethod`.
"""
encode_erc1155_asset_data: EncodeErc1155AssetDataMethod
"""Constructor-initialized instance of
:class:`EncodeErc1155AssetDataMethod`.
"""
encode_erc20_asset_data: EncodeErc20AssetDataMethod
"""Constructor-initialized instance of
:class:`EncodeErc20AssetDataMethod`.
"""
encode_erc721_asset_data: EncodeErc721AssetDataMethod
"""Constructor-initialized instance of
:class:`EncodeErc721AssetDataMethod`.
"""
encode_multi_asset_data: EncodeMultiAssetDataMethod
"""Constructor-initialized instance of
:class:`EncodeMultiAssetDataMethod`.
"""
encode_static_call_asset_data: EncodeStaticCallAssetDataMethod
"""Constructor-initialized instance of
:class:`EncodeStaticCallAssetDataMethod`.
"""
get_asset_proxy_allowance: GetAssetProxyAllowanceMethod
"""Constructor-initialized instance of
:class:`GetAssetProxyAllowanceMethod`.
"""
get_balance: GetBalanceMethod
"""Constructor-initialized instance of
:class:`GetBalanceMethod`.
"""
get_balance_and_asset_proxy_allowance: GetBalanceAndAssetProxyAllowanceMethod
"""Constructor-initialized instance of
:class:`GetBalanceAndAssetProxyAllowanceMethod`.
"""
get_batch_asset_proxy_allowances: GetBatchAssetProxyAllowancesMethod
"""Constructor-initialized instance of
:class:`GetBatchAssetProxyAllowancesMethod`.
"""
get_batch_balances: GetBatchBalancesMethod
"""Constructor-initialized instance of
:class:`GetBatchBalancesMethod`.
"""
get_batch_balances_and_asset_proxy_allowances: GetBatchBalancesAndAssetProxyAllowancesMethod
"""Constructor-initialized instance of
:class:`GetBatchBalancesAndAssetProxyAllowancesMethod`.
"""
get_eth_balances: GetEthBalancesMethod
"""Constructor-initialized instance of
:class:`GetEthBalancesMethod`.
"""
get_order_hash: GetOrderHashMethod
"""Constructor-initialized instance of
:class:`GetOrderHashMethod`.
"""
get_order_relevant_state: GetOrderRelevantStateMethod
"""Constructor-initialized instance of
:class:`GetOrderRelevantStateMethod`.
"""
get_order_relevant_states: GetOrderRelevantStatesMethod
"""Constructor-initialized instance of
:class:`GetOrderRelevantStatesMethod`.
"""
get_simulated_order_transfer_results: GetSimulatedOrderTransferResultsMethod
"""Constructor-initialized instance of
:class:`GetSimulatedOrderTransferResultsMethod`.
"""
get_simulated_orders_transfer_results: GetSimulatedOrdersTransferResultsMethod
"""Constructor-initialized instance of
:class:`GetSimulatedOrdersTransferResultsMethod`.
"""
get_transaction_hash: GetTransactionHashMethod
"""Constructor-initialized instance of
:class:`GetTransactionHashMethod`.
"""
get_transferable_asset_amount: GetTransferableAssetAmountMethod
"""Constructor-initialized instance of
:class:`GetTransferableAssetAmountMethod`.
"""
revert_if_invalid_asset_data: RevertIfInvalidAssetDataMethod
"""Constructor-initialized instance of
:class:`RevertIfInvalidAssetDataMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: DevUtilsValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = DevUtilsValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=DevUtils.abi()
).functions
self.eip712_exchange_domain_hash = Eip712ExchangeDomainHashMethod(
web3_or_provider,
contract_address,
functions.EIP712_EXCHANGE_DOMAIN_HASH,
)
self.decode_asset_proxy_dispatch_error = DecodeAssetProxyDispatchErrorMethod(
web3_or_provider,
contract_address,
functions.decodeAssetProxyDispatchError,
validator,
)
self.decode_asset_proxy_exists_error = DecodeAssetProxyExistsErrorMethod(
web3_or_provider,
contract_address,
functions.decodeAssetProxyExistsError,
validator,
)
self.decode_asset_proxy_id = DecodeAssetProxyIdMethod(
web3_or_provider,
contract_address,
functions.decodeAssetProxyId,
validator,
)
self.decode_asset_proxy_transfer_error = DecodeAssetProxyTransferErrorMethod(
web3_or_provider,
contract_address,
functions.decodeAssetProxyTransferError,
validator,
)
self.decode_eip1271_signature_error = DecodeEip1271SignatureErrorMethod(
web3_or_provider,
contract_address,
functions.decodeEIP1271SignatureError,
validator,
)
self.decode_erc1155_asset_data = DecodeErc1155AssetDataMethod(
web3_or_provider,
contract_address,
functions.decodeERC1155AssetData,
validator,
)
self.decode_erc20_asset_data = DecodeErc20AssetDataMethod(
web3_or_provider,
contract_address,
functions.decodeERC20AssetData,
validator,
)
self.decode_erc721_asset_data = DecodeErc721AssetDataMethod(
web3_or_provider,
contract_address,
functions.decodeERC721AssetData,
validator,
)
self.decode_exchange_invalid_context_error = DecodeExchangeInvalidContextErrorMethod(
web3_or_provider,
contract_address,
functions.decodeExchangeInvalidContextError,
validator,
)
self.decode_fill_error = DecodeFillErrorMethod(
web3_or_provider,
contract_address,
functions.decodeFillError,
validator,
)
self.decode_incomplete_fill_error = DecodeIncompleteFillErrorMethod(
web3_or_provider,
contract_address,
functions.decodeIncompleteFillError,
validator,
)
self.decode_multi_asset_data = DecodeMultiAssetDataMethod(
web3_or_provider,
contract_address,
functions.decodeMultiAssetData,
validator,
)
self.decode_negative_spread_error = DecodeNegativeSpreadErrorMethod(
web3_or_provider,
contract_address,
functions.decodeNegativeSpreadError,
validator,
)
self.decode_order_epoch_error = DecodeOrderEpochErrorMethod(
web3_or_provider,
contract_address,
functions.decodeOrderEpochError,
validator,
)
self.decode_order_status_error = DecodeOrderStatusErrorMethod(
web3_or_provider,
contract_address,
functions.decodeOrderStatusError,
validator,
)
self.decode_signature_error = DecodeSignatureErrorMethod(
web3_or_provider,
contract_address,
functions.decodeSignatureError,
validator,
)
self.decode_signature_validator_not_approved_error = DecodeSignatureValidatorNotApprovedErrorMethod(
web3_or_provider,
contract_address,
functions.decodeSignatureValidatorNotApprovedError,
validator,
)
self.decode_signature_wallet_error = DecodeSignatureWalletErrorMethod(
web3_or_provider,
contract_address,
functions.decodeSignatureWalletError,
validator,
)
self.decode_static_call_asset_data = DecodeStaticCallAssetDataMethod(
web3_or_provider,
contract_address,
functions.decodeStaticCallAssetData,
validator,
)
self.decode_transaction_error = DecodeTransactionErrorMethod(
web3_or_provider,
contract_address,
functions.decodeTransactionError,
validator,
)
self.decode_transaction_execution_error = DecodeTransactionExecutionErrorMethod(
web3_or_provider,
contract_address,
functions.decodeTransactionExecutionError,
validator,
)
self.decode_zero_ex_transaction_data = DecodeZeroExTransactionDataMethod(
web3_or_provider,
contract_address,
functions.decodeZeroExTransactionData,
validator,
)
self.encode_erc1155_asset_data = EncodeErc1155AssetDataMethod(
web3_or_provider,
contract_address,
functions.encodeERC1155AssetData,
validator,
)
self.encode_erc20_asset_data = EncodeErc20AssetDataMethod(
web3_or_provider,
contract_address,
functions.encodeERC20AssetData,
validator,
)
self.encode_erc721_asset_data = EncodeErc721AssetDataMethod(
web3_or_provider,
contract_address,
functions.encodeERC721AssetData,
validator,
)
self.encode_multi_asset_data = EncodeMultiAssetDataMethod(
web3_or_provider,
contract_address,
functions.encodeMultiAssetData,
validator,
)
self.encode_static_call_asset_data = EncodeStaticCallAssetDataMethod(
web3_or_provider,
contract_address,
functions.encodeStaticCallAssetData,
validator,
)
self.get_asset_proxy_allowance = GetAssetProxyAllowanceMethod(
web3_or_provider,
contract_address,
functions.getAssetProxyAllowance,
validator,
)
self.get_balance = GetBalanceMethod(
web3_or_provider, contract_address, functions.getBalance, validator
)
self.get_balance_and_asset_proxy_allowance = GetBalanceAndAssetProxyAllowanceMethod(
web3_or_provider,
contract_address,
functions.getBalanceAndAssetProxyAllowance,
validator,
)
self.get_batch_asset_proxy_allowances = GetBatchAssetProxyAllowancesMethod(
web3_or_provider,
contract_address,
functions.getBatchAssetProxyAllowances,
validator,
)
self.get_batch_balances = GetBatchBalancesMethod(
web3_or_provider,
contract_address,
functions.getBatchBalances,
validator,
)
self.get_batch_balances_and_asset_proxy_allowances = GetBatchBalancesAndAssetProxyAllowancesMethod(
web3_or_provider,
contract_address,
functions.getBatchBalancesAndAssetProxyAllowances,
validator,
)
self.get_eth_balances = GetEthBalancesMethod(
web3_or_provider,
contract_address,
functions.getEthBalances,
validator,
)
self.get_order_hash = GetOrderHashMethod(
web3_or_provider,
contract_address,
functions.getOrderHash,
validator,
)
self.get_order_relevant_state = GetOrderRelevantStateMethod(
web3_or_provider,
contract_address,
functions.getOrderRelevantState,
validator,
)
self.get_order_relevant_states = GetOrderRelevantStatesMethod(
web3_or_provider,
contract_address,
functions.getOrderRelevantStates,
validator,
)
self.get_simulated_order_transfer_results = GetSimulatedOrderTransferResultsMethod(
web3_or_provider,
contract_address,
functions.getSimulatedOrderTransferResults,
validator,
)
self.get_simulated_orders_transfer_results = GetSimulatedOrdersTransferResultsMethod(
web3_or_provider,
contract_address,
functions.getSimulatedOrdersTransferResults,
validator,
)
self.get_transaction_hash = GetTransactionHashMethod(
web3_or_provider,
contract_address,
functions.getTransactionHash,
validator,
)
self.get_transferable_asset_amount = GetTransferableAssetAmountMethod(
web3_or_provider,
contract_address,
functions.getTransferableAssetAmount,
validator,
)
self.revert_if_invalid_asset_data = RevertIfInvalidAssetDataMethod(
web3_or_provider,
contract_address,
functions.revertIfInvalidAssetData,
validator,
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"address","name":"_exchange","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"constant":true,"inputs":[],"name":"EIP712_EXCHANGE_DOMAIN_HASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeAssetProxyDispatchError","outputs":[{"internalType":"enum LibExchangeRichErrors.AssetProxyDispatchErrorCodes","name":"errorCode","type":"uint8"},{"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"internalType":"bytes","name":"assetData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeAssetProxyExistsError","outputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"},{"internalType":"address","name":"assetProxyAddress","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"decodeAssetProxyId","outputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeAssetProxyTransferError","outputs":[{"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"internalType":"bytes","name":"assetData","type":"bytes"},{"internalType":"bytes","name":"errorData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeEIP1271SignatureError","outputs":[{"internalType":"address","name":"verifyingContractAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"bytes","name":"signature","type":"bytes"},{"internalType":"bytes","name":"errorData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"decodeERC1155AssetData","outputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"uint256[]","name":"tokenValues","type":"uint256[]"},{"internalType":"bytes","name":"callbackData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"decodeERC20AssetData","outputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"},{"internalType":"address","name":"tokenAddress","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"decodeERC721AssetData","outputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeExchangeInvalidContextError","outputs":[{"internalType":"enum LibExchangeRichErrors.ExchangeContextErrorCodes","name":"errorCode","type":"uint8"},{"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"internalType":"address","name":"contextAddress","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeFillError","outputs":[{"internalType":"enum LibExchangeRichErrors.FillErrorCodes","name":"errorCode","type":"uint8"},{"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeIncompleteFillError","outputs":[{"internalType":"enum LibExchangeRichErrors.IncompleteFillErrorCode","name":"errorCode","type":"uint8"},{"internalType":"uint256","name":"expectedAssetFillAmount","type":"uint256"},{"internalType":"uint256","name":"actualAssetFillAmount","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"decodeMultiAssetData","outputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"bytes[]","name":"nestedAssetData","type":"bytes[]"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeNegativeSpreadError","outputs":[{"internalType":"bytes32","name":"leftOrderHash","type":"bytes32"},{"internalType":"bytes32","name":"rightOrderHash","type":"bytes32"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeOrderEpochError","outputs":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"orderSenderAddress","type":"address"},{"internalType":"uint256","name":"currentEpoch","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeOrderStatusError","outputs":[{"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"internalType":"enum LibOrder.OrderStatus","name":"orderStatus","type":"uint8"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeSignatureError","outputs":[{"internalType":"enum LibExchangeRichErrors.SignatureErrorCodes","name":"errorCode","type":"uint8"},{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeSignatureValidatorNotApprovedError","outputs":[{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"address","name":"validatorAddress","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeSignatureWalletError","outputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"},{"internalType":"bytes","name":"errorData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"decodeStaticCallAssetData","outputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"},{"internalType":"address","name":"staticCallTargetAddress","type":"address"},{"internalType":"bytes","name":"staticCallData","type":"bytes"},{"internalType":"bytes32","name":"expectedReturnDataHash","type":"bytes32"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeTransactionError","outputs":[{"internalType":"enum LibExchangeRichErrors.TransactionErrorCodes","name":"errorCode","type":"uint8"},{"internalType":"bytes32","name":"transactionHash","type":"bytes32"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"encoded","type":"bytes"}],"name":"decodeTransactionExecutionError","outputs":[{"internalType":"bytes32","name":"transactionHash","type":"bytes32"},{"internalType":"bytes","name":"errorData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"transactionData","type":"bytes"}],"name":"decodeZeroExTransactionData","outputs":[{"internalType":"string","name":"functionName","type":"string"},{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256[]","name":"takerAssetFillAmounts","type":"uint256[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"uint256[]","name":"tokenValues","type":"uint256[]"},{"internalType":"bytes","name":"callbackData","type":"bytes"}],"name":"encodeERC1155AssetData","outputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"encodeERC20AssetData","outputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"encodeERC721AssetData","outputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"bytes[]","name":"nestedAssetData","type":"bytes[]"}],"name":"encodeMultiAssetData","outputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"staticCallTargetAddress","type":"address"},{"internalType":"bytes","name":"staticCallData","type":"bytes"},{"internalType":"bytes32","name":"expectedReturnDataHash","type":"bytes32"}],"name":"encodeStaticCallAssetData","outputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"ownerAddress","type":"address"},{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"getAssetProxyAllowance","outputs":[{"internalType":"uint256","name":"allowance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"ownerAddress","type":"address"},{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"getBalance","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"ownerAddress","type":"address"},{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"getBalanceAndAssetProxyAllowance","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"allowance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"ownerAddress","type":"address"},{"internalType":"bytes[]","name":"assetData","type":"bytes[]"}],"name":"getBatchAssetProxyAllowances","outputs":[{"internalType":"uint256[]","name":"allowances","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"ownerAddress","type":"address"},{"internalType":"bytes[]","name":"assetData","type":"bytes[]"}],"name":"getBatchBalances","outputs":[{"internalType":"uint256[]","name":"balances","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"ownerAddress","type":"address"},{"internalType":"bytes[]","name":"assetData","type":"bytes[]"}],"name":"getBatchBalancesAndAssetProxyAllowances","outputs":[{"internalType":"uint256[]","name":"balances","type":"uint256[]"},{"internalType":"uint256[]","name":"allowances","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address[]","name":"addresses","type":"address[]"}],"name":"getEthBalances","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"order","type":"tuple"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"exchange","type":"address"}],"name":"getOrderHash","outputs":[{"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"order","type":"tuple"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"getOrderRelevantState","outputs":[{"components":[{"internalType":"uint8","name":"orderStatus","type":"uint8"},{"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"internalType":"uint256","name":"orderTakerAssetFilledAmount","type":"uint256"}],"internalType":"struct LibOrder.OrderInfo","name":"orderInfo","type":"tuple"},{"internalType":"uint256","name":"fillableTakerAssetAmount","type":"uint256"},{"internalType":"bool","name":"isValidSignature","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"getOrderRelevantStates","outputs":[{"components":[{"internalType":"uint8","name":"orderStatus","type":"uint8"},{"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"internalType":"uint256","name":"orderTakerAssetFilledAmount","type":"uint256"}],"internalType":"struct LibOrder.OrderInfo[]","name":"ordersInfo","type":"tuple[]"},{"internalType":"uint256[]","name":"fillableTakerAssetAmounts","type":"uint256[]"},{"internalType":"bool[]","name":"isValidSignature","type":"bool[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"order","type":"tuple"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"uint256","name":"takerAssetFillAmount","type":"uint256"}],"name":"getSimulatedOrderTransferResults","outputs":[{"internalType":"enum OrderTransferSimulationUtils.OrderTransferResults","name":"orderTransferResults","type":"uint8"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"address[]","name":"takerAddresses","type":"address[]"},{"internalType":"uint256[]","name":"takerAssetFillAmounts","type":"uint256[]"}],"name":"getSimulatedOrdersTransferResults","outputs":[{"internalType":"enum OrderTransferSimulationUtils.OrderTransferResults[]","name":"orderTransferResults","type":"uint8[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"gasPrice","type":"uint256"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct LibZeroExTransaction.ZeroExTransaction","name":"transaction","type":"tuple"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"exchange","type":"address"}],"name":"getTransactionHash","outputs":[{"internalType":"bytes32","name":"transactionHash","type":"bytes32"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"ownerAddress","type":"address"},{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"getTransferableAssetAmount","outputs":[{"internalType":"uint256","name":"transferableAssetAmount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"revertIfInvalidAssetData","outputs":[],"payable":false,"stateMutability":"pure","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/dev_utils/__init__.py | __init__.py |
"""Generated wrapper for DummyERC721Token Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for DummyERC721Token below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
DummyERC721TokenValidator,
)
except ImportError:
class DummyERC721TokenValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class ApproveMethod(ContractMethod):
"""Various interfaces to the approve method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _approved: str, _token_id: int):
"""Validate the inputs to the approve method."""
self.validator.assert_valid(
method_name="approve",
parameter_name="_approved",
argument_value=_approved,
)
_approved = self.validate_and_checksum_address(_approved)
self.validator.assert_valid(
method_name="approve",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return (_approved, _token_id)
def call(
self,
_approved: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
The zero address indicates there is no approved address. Throws unless
`msg.sender` is the current NFT owner, or an authorized operator of the
current owner.
:param _approved: The new approved NFT controller
:param _tokenId: The NFT to approve
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_approved, _token_id) = self.validate_and_normalize_inputs(
_approved, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_approved, _token_id).call(tx_params.as_dict())
def send_transaction(
self,
_approved: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
The zero address indicates there is no approved address. Throws unless
`msg.sender` is the current NFT owner, or an authorized operator of the
current owner.
:param _approved: The new approved NFT controller
:param _tokenId: The NFT to approve
:param tx_params: transaction parameters
"""
(_approved, _token_id) = self.validate_and_normalize_inputs(
_approved, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_approved, _token_id).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_approved: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_approved, _token_id) = self.validate_and_normalize_inputs(
_approved, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_approved, _token_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_approved: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_approved, _token_id) = self.validate_and_normalize_inputs(
_approved, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_approved, _token_id).estimateGas(
tx_params.as_dict()
)
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
return _owner
def call(self, _owner: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
NFTs assigned to the zero address are considered invalid, and this
function throws for queries about the zero address.
:param _owner: An address for whom to query the balance
:param tx_params: transaction parameters
:returns: The number of NFTs owned by `_owner`, possibly zero
"""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, _owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner).estimateGas(tx_params.as_dict())
class BurnMethod(ContractMethod):
"""Various interfaces to the burn method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str, _token_id: int):
"""Validate the inputs to the burn method."""
self.validator.assert_valid(
method_name="burn", parameter_name="_owner", argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
self.validator.assert_valid(
method_name="burn",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return (_owner, _token_id)
def call(
self, _owner: str, _token_id: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Function to burn a token Reverts if the given token ID doesn't exist or
not called by contract owner
:param _owner: Owner of token with given token ID
:param _tokenId: ID of the token to be burned by the msg.sender
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_owner, _token_id) = self.validate_and_normalize_inputs(
_owner, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_owner, _token_id).call(tx_params.as_dict())
def send_transaction(
self, _owner: str, _token_id: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Function to burn a token Reverts if the given token ID doesn't exist or
not called by contract owner
:param _owner: Owner of token with given token ID
:param _tokenId: ID of the token to be burned by the msg.sender
:param tx_params: transaction parameters
"""
(_owner, _token_id) = self.validate_and_normalize_inputs(
_owner, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner, _token_id).transact(
tx_params.as_dict()
)
def build_transaction(
self, _owner: str, _token_id: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_owner, _token_id) = self.validate_and_normalize_inputs(
_owner, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner, _token_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _owner: str, _token_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner, _token_id) = self.validate_and_normalize_inputs(
_owner, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner, _token_id).estimateGas(
tx_params.as_dict()
)
class GetApprovedMethod(ContractMethod):
"""Various interfaces to the getApproved method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _token_id: int):
"""Validate the inputs to the getApproved method."""
self.validator.assert_valid(
method_name="getApproved",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return _token_id
def call(
self, _token_id: int, tx_params: Optional[TxParams] = None
) -> str:
"""Execute underlying contract method via eth_call.
Throws if `_tokenId` is not a valid NFT.
:param _tokenId: The NFT to find the approved address for
:param tx_params: transaction parameters
:returns: The approved address for this NFT, or the zero address if
there is none
"""
(_token_id) = self.validate_and_normalize_inputs(_token_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_token_id).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, _token_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_token_id) = self.validate_and_normalize_inputs(_token_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_token_id).estimateGas(
tx_params.as_dict()
)
class IsApprovedForAllMethod(ContractMethod):
"""Various interfaces to the isApprovedForAll method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str, _operator: str):
"""Validate the inputs to the isApprovedForAll method."""
self.validator.assert_valid(
method_name="isApprovedForAll",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
self.validator.assert_valid(
method_name="isApprovedForAll",
parameter_name="_operator",
argument_value=_operator,
)
_operator = self.validate_and_checksum_address(_operator)
return (_owner, _operator)
def call(
self, _owner: str, _operator: str, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param _operator: The address that acts on behalf of the owner
:param _owner: The address that owns the NFTs
:param tx_params: transaction parameters
:returns: True if `_operator` is an approved operator for `_owner`,
false otherwise
"""
(_owner, _operator) = self.validate_and_normalize_inputs(
_owner, _operator
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner, _operator).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self, _owner: str, _operator: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner, _operator) = self.validate_and_normalize_inputs(
_owner, _operator
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner, _operator).estimateGas(
tx_params.as_dict()
)
class MintMethod(ContractMethod):
"""Various interfaces to the mint method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _to: str, _token_id: int):
"""Validate the inputs to the mint method."""
self.validator.assert_valid(
method_name="mint", parameter_name="_to", argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="mint",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return (_to, _token_id)
def call(
self, _to: str, _token_id: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Function to mint a new token Reverts if the given token ID already
exists
:param _to: Address of the beneficiary that will own the minted token
:param _tokenId: ID of the token to be minted by the msg.sender
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_to, _token_id) = self.validate_and_normalize_inputs(_to, _token_id)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_to, _token_id).call(tx_params.as_dict())
def send_transaction(
self, _to: str, _token_id: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Function to mint a new token Reverts if the given token ID already
exists
:param _to: Address of the beneficiary that will own the minted token
:param _tokenId: ID of the token to be minted by the msg.sender
:param tx_params: transaction parameters
"""
(_to, _token_id) = self.validate_and_normalize_inputs(_to, _token_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _token_id).transact(
tx_params.as_dict()
)
def build_transaction(
self, _to: str, _token_id: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_to, _token_id) = self.validate_and_normalize_inputs(_to, _token_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _token_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _to: str, _token_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_to, _token_id) = self.validate_and_normalize_inputs(_to, _token_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _token_id).estimateGas(
tx_params.as_dict()
)
class NameMethod(ContractMethod):
"""Various interfaces to the name method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class OwnerOfMethod(ContractMethod):
"""Various interfaces to the ownerOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _token_id: int):
"""Validate the inputs to the ownerOf method."""
self.validator.assert_valid(
method_name="ownerOf",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return _token_id
def call(
self, _token_id: int, tx_params: Optional[TxParams] = None
) -> str:
"""Execute underlying contract method via eth_call.
NFTs assigned to zero address are considered invalid, and queries about
them do throw.
:param _tokenId: The identifier for an NFT
:param tx_params: transaction parameters
:returns: The address of the owner of the NFT
"""
(_token_id) = self.validate_and_normalize_inputs(_token_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_token_id).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, _token_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_token_id) = self.validate_and_normalize_inputs(_token_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_token_id).estimateGas(
tx_params.as_dict()
)
class SafeTransferFrom1Method(ContractMethod):
"""Various interfaces to the safeTransferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _from: str, _to: str, _token_id: int
):
"""Validate the inputs to the safeTransferFrom method."""
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return (_from, _to, _token_id)
def call(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
This works identically to the other function with an extra data
parameter, except this function just sets data to "".
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, _to, _token_id).call(
tx_params.as_dict()
)
def send_transaction(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
This works identically to the other function with an extra data
parameter, except this function just sets data to "".
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
"""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).estimateGas(
tx_params.as_dict()
)
class SafeTransferFrom2Method(ContractMethod):
"""Various interfaces to the safeTransferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _from: str, _to: str, _token_id: int, _data: Union[bytes, str]
):
"""Validate the inputs to the safeTransferFrom method."""
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_data",
argument_value=_data,
)
return (_from, _to, _token_id, _data)
def call(
self,
_from: str,
_to: str,
_token_id: int,
_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Throws unless `msg.sender` is the current owner, an authorized
operator, or the approved address for this NFT. Throws if `_from` is
not the current owner. Throws if `_to` is the zero address. Throws if
`_tokenId` is not a valid NFT. When transfer is complete, this function
checks if `_to` is a smart contract (code size > 0). If so, it calls
`onERC721Received` on `_to` and throws if the return value is not
`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
:param _data: Additional data with no specified format, sent in call to
`_to`
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _token_id, _data) = self.validate_and_normalize_inputs(
_from, _to, _token_id, _data
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, _to, _token_id, _data).call(
tx_params.as_dict()
)
def send_transaction(
self,
_from: str,
_to: str,
_token_id: int,
_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Throws unless `msg.sender` is the current owner, an authorized
operator, or the approved address for this NFT. Throws if `_from` is
not the current owner. Throws if `_to` is the zero address. Throws if
`_tokenId` is not a valid NFT. When transfer is complete, this function
checks if `_to` is a smart contract (code size > 0). If so, it calls
`onERC721Received` on `_to` and throws if the return value is not
`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
:param _data: Additional data with no specified format, sent in call to
`_to`
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
"""
(_from, _to, _token_id, _data) = self.validate_and_normalize_inputs(
_from, _to, _token_id, _data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id, _data).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_token_id: int,
_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _token_id, _data) = self.validate_and_normalize_inputs(
_from, _to, _token_id, _data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, _to, _token_id, _data
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
_from: str,
_to: str,
_token_id: int,
_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _token_id, _data) = self.validate_and_normalize_inputs(
_from, _to, _token_id, _data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, _to, _token_id, _data
).estimateGas(tx_params.as_dict())
class SetApprovalForAllMethod(ContractMethod):
"""Various interfaces to the setApprovalForAll method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _operator: str, _approved: bool):
"""Validate the inputs to the setApprovalForAll method."""
self.validator.assert_valid(
method_name="setApprovalForAll",
parameter_name="_operator",
argument_value=_operator,
)
_operator = self.validate_and_checksum_address(_operator)
self.validator.assert_valid(
method_name="setApprovalForAll",
parameter_name="_approved",
argument_value=_approved,
)
return (_operator, _approved)
def call(
self,
_operator: str,
_approved: bool,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Emits the ApprovalForAll event. The contract MUST allow multiple
operators per owner.
:param _approved: True if the operator is approved, false to revoke
approval
:param _operator: Address to add to the set of authorized operators
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_operator, _approved) = self.validate_and_normalize_inputs(
_operator, _approved
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_operator, _approved).call(tx_params.as_dict())
def send_transaction(
self,
_operator: str,
_approved: bool,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Emits the ApprovalForAll event. The contract MUST allow multiple
operators per owner.
:param _approved: True if the operator is approved, false to revoke
approval
:param _operator: Address to add to the set of authorized operators
:param tx_params: transaction parameters
"""
(_operator, _approved) = self.validate_and_normalize_inputs(
_operator, _approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_operator, _approved).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_operator: str,
_approved: bool,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_operator, _approved) = self.validate_and_normalize_inputs(
_operator, _approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_operator, _approved).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_operator: str,
_approved: bool,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_operator, _approved) = self.validate_and_normalize_inputs(
_operator, _approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_operator, _approved).estimateGas(
tx_params.as_dict()
)
class SymbolMethod(ContractMethod):
"""Various interfaces to the symbol method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _from: str, _to: str, _token_id: int
):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return (_from, _to, _token_id)
def call(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Throws unless `msg.sender` is the current owner, an authorized
operator, or the approved address for this NFT. Throws if `_from` is
not the current owner. Throws if `_to` is the zero address. Throws if
`_tokenId` is not a valid NFT.
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, _to, _token_id).call(
tx_params.as_dict()
)
def send_transaction(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Throws unless `msg.sender` is the current owner, an authorized
operator, or the approved address for this NFT. Throws if `_from` is
not the current owner. Throws if `_to` is the zero address. Throws if
`_tokenId` is not a valid NFT.
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
"""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).estimateGas(
tx_params.as_dict()
)
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class DummyERC721Token:
"""Wrapper class for DummyERC721Token Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
approve: ApproveMethod
"""Constructor-initialized instance of
:class:`ApproveMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
burn: BurnMethod
"""Constructor-initialized instance of
:class:`BurnMethod`.
"""
get_approved: GetApprovedMethod
"""Constructor-initialized instance of
:class:`GetApprovedMethod`.
"""
is_approved_for_all: IsApprovedForAllMethod
"""Constructor-initialized instance of
:class:`IsApprovedForAllMethod`.
"""
mint: MintMethod
"""Constructor-initialized instance of
:class:`MintMethod`.
"""
name: NameMethod
"""Constructor-initialized instance of
:class:`NameMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
owner_of: OwnerOfMethod
"""Constructor-initialized instance of
:class:`OwnerOfMethod`.
"""
safe_transfer_from1: SafeTransferFrom1Method
"""Constructor-initialized instance of
:class:`SafeTransferFrom1Method`.
"""
safe_transfer_from2: SafeTransferFrom2Method
"""Constructor-initialized instance of
:class:`SafeTransferFrom2Method`.
"""
set_approval_for_all: SetApprovalForAllMethod
"""Constructor-initialized instance of
:class:`SetApprovalForAllMethod`.
"""
symbol: SymbolMethod
"""Constructor-initialized instance of
:class:`SymbolMethod`.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: DummyERC721TokenValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = DummyERC721TokenValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=DummyERC721Token.abi(),
).functions
self.approve = ApproveMethod(
web3_or_provider, contract_address, functions.approve, validator
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.burn = BurnMethod(
web3_or_provider, contract_address, functions.burn, validator
)
self.get_approved = GetApprovedMethod(
web3_or_provider,
contract_address,
functions.getApproved,
validator,
)
self.is_approved_for_all = IsApprovedForAllMethod(
web3_or_provider,
contract_address,
functions.isApprovedForAll,
validator,
)
self.mint = MintMethod(
web3_or_provider, contract_address, functions.mint, validator
)
self.name = NameMethod(
web3_or_provider, contract_address, functions.name
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.owner_of = OwnerOfMethod(
web3_or_provider, contract_address, functions.ownerOf, validator
)
self.safe_transfer_from1 = SafeTransferFrom1Method(
web3_or_provider,
contract_address,
functions.safeTransferFrom,
validator,
)
self.safe_transfer_from2 = SafeTransferFrom2Method(
web3_or_provider,
contract_address,
functions.safeTransferFrom,
validator,
)
self.set_approval_for_all = SetApprovalForAllMethod(
web3_or_provider,
contract_address,
functions.setApprovalForAll,
validator,
)
self.symbol = SymbolMethod(
web3_or_provider, contract_address, functions.symbol
)
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
def get_approval_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Approval event.
:param tx_hash: hash of transaction emitting Approval event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=DummyERC721Token.abi(),
)
.events.Approval()
.processReceipt(tx_receipt)
)
def get_approval_for_all_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ApprovalForAll event.
:param tx_hash: hash of transaction emitting ApprovalForAll event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=DummyERC721Token.abi(),
)
.events.ApprovalForAll()
.processReceipt(tx_receipt)
)
def get_transfer_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Transfer event.
:param tx_hash: hash of transaction emitting Transfer event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=DummyERC721Token.abi(),
)
.events.Transfer()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_operator","type":"address"},{"indexed":false,"internalType":"bool","name":"_approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":true,"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"constant":false,"inputs":[{"internalType":"address","name":"_approved","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_operator","type":"address"},{"internalType":"bool","name":"_approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/dummy_erc721_token/__init__.py | __init__.py |
"""Generated wrapper for AssetProxyOwner Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for AssetProxyOwner below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
AssetProxyOwnerValidator,
)
except ImportError:
class AssetProxyOwnerValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class MaxOwnerCountMethod(ContractMethod):
"""Various interfaces to the MAX_OWNER_COUNT method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AddOwnerMethod(ContractMethod):
"""Various interfaces to the addOwner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, owner: str):
"""Validate the inputs to the addOwner method."""
self.validator.assert_valid(
method_name="addOwner",
parameter_name="owner",
argument_value=owner,
)
owner = self.validate_and_checksum_address(owner)
return owner
def call(self, owner: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Allows to add a new owner. Transaction has to be sent by wallet.
:param owner: Address of new owner.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(owner) = self.validate_and_normalize_inputs(owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(owner).call(tx_params.as_dict())
def send_transaction(
self, owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows to add a new owner. Transaction has to be sent by wallet.
:param owner: Address of new owner.
:param tx_params: transaction parameters
"""
(owner) = self.validate_and_normalize_inputs(owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner).transact(tx_params.as_dict())
def build_transaction(
self, owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(owner) = self.validate_and_normalize_inputs(owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(owner) = self.validate_and_normalize_inputs(owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner).estimateGas(tx_params.as_dict())
class ChangeRequirementMethod(ContractMethod):
"""Various interfaces to the changeRequirement method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _required: int):
"""Validate the inputs to the changeRequirement method."""
self.validator.assert_valid(
method_name="changeRequirement",
parameter_name="_required",
argument_value=_required,
)
# safeguard against fractional inputs
_required = int(_required)
return _required
def call(
self, _required: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Allows to change the number of required confirmations. Transaction has
to be sent by wallet.
:param _required: Number of required confirmations.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_required) = self.validate_and_normalize_inputs(_required)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_required).call(tx_params.as_dict())
def send_transaction(
self, _required: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows to change the number of required confirmations. Transaction has
to be sent by wallet.
:param _required: Number of required confirmations.
:param tx_params: transaction parameters
"""
(_required) = self.validate_and_normalize_inputs(_required)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_required).transact(tx_params.as_dict())
def build_transaction(
self, _required: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_required) = self.validate_and_normalize_inputs(_required)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_required).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _required: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_required) = self.validate_and_normalize_inputs(_required)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_required).estimateGas(
tx_params.as_dict()
)
class ChangeTimeLockMethod(ContractMethod):
"""Various interfaces to the changeTimeLock method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _seconds_time_locked: int):
"""Validate the inputs to the changeTimeLock method."""
self.validator.assert_valid(
method_name="changeTimeLock",
parameter_name="_secondsTimeLocked",
argument_value=_seconds_time_locked,
)
# safeguard against fractional inputs
_seconds_time_locked = int(_seconds_time_locked)
return _seconds_time_locked
def call(
self, _seconds_time_locked: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Changes the duration of the time lock for transactions.
:param _secondsTimeLocked: Duration needed after a transaction is
confirmed and before it becomes executable, in seconds.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_seconds_time_locked) = self.validate_and_normalize_inputs(
_seconds_time_locked
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_seconds_time_locked).call(tx_params.as_dict())
def send_transaction(
self, _seconds_time_locked: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Changes the duration of the time lock for transactions.
:param _secondsTimeLocked: Duration needed after a transaction is
confirmed and before it becomes executable, in seconds.
:param tx_params: transaction parameters
"""
(_seconds_time_locked) = self.validate_and_normalize_inputs(
_seconds_time_locked
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_seconds_time_locked).transact(
tx_params.as_dict()
)
def build_transaction(
self, _seconds_time_locked: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_seconds_time_locked) = self.validate_and_normalize_inputs(
_seconds_time_locked
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_seconds_time_locked).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _seconds_time_locked: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_seconds_time_locked) = self.validate_and_normalize_inputs(
_seconds_time_locked
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_seconds_time_locked).estimateGas(
tx_params.as_dict()
)
class ConfirmTransactionMethod(ContractMethod):
"""Various interfaces to the confirmTransaction method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, transaction_id: int):
"""Validate the inputs to the confirmTransaction method."""
self.validator.assert_valid(
method_name="confirmTransaction",
parameter_name="transactionId",
argument_value=transaction_id,
)
# safeguard against fractional inputs
transaction_id = int(transaction_id)
return transaction_id
def call(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Allows an owner to confirm a transaction.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(transaction_id).call(tx_params.as_dict())
def send_transaction(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows an owner to confirm a transaction.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).transact(
tx_params.as_dict()
)
def build_transaction(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).estimateGas(
tx_params.as_dict()
)
class ConfirmationTimesMethod(ContractMethod):
"""Various interfaces to the confirmationTimes method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the confirmationTimes method."""
self.validator.assert_valid(
method_name="confirmationTimes",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class ConfirmationsMethod(ContractMethod):
"""Various interfaces to the confirmations method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int, index_1: str):
"""Validate the inputs to the confirmations method."""
self.validator.assert_valid(
method_name="confirmations",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
self.validator.assert_valid(
method_name="confirmations",
parameter_name="index_1",
argument_value=index_1,
)
index_1 = self.validate_and_checksum_address(index_1)
return (index_0, index_1)
def call(
self, index_0: int, index_1: str, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0, index_1).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self, index_0: int, index_1: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0, index_1).estimateGas(
tx_params.as_dict()
)
class ExecuteTransactionMethod(ContractMethod):
"""Various interfaces to the executeTransaction method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, transaction_id: int):
"""Validate the inputs to the executeTransaction method."""
self.validator.assert_valid(
method_name="executeTransaction",
parameter_name="transactionId",
argument_value=transaction_id,
)
# safeguard against fractional inputs
transaction_id = int(transaction_id)
return transaction_id
def call(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Allows anyone to execute a confirmed transaction. Transactions *must*
encode the values with the signature "bytes[] data, address[]
destinations, uint256[] values" The `destination` and `value` fields of
the transaction in storage are ignored. All function calls must be
successful or the entire call will revert.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(transaction_id).call(tx_params.as_dict())
def send_transaction(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows anyone to execute a confirmed transaction. Transactions *must*
encode the values with the signature "bytes[] data, address[]
destinations, uint256[] values" The `destination` and `value` fields of
the transaction in storage are ignored. All function calls must be
successful or the entire call will revert.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).transact(
tx_params.as_dict()
)
def build_transaction(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).estimateGas(
tx_params.as_dict()
)
class FunctionCallTimeLocksMethod(ContractMethod):
"""Various interfaces to the functionCallTimeLocks method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, index_0: Union[bytes, str], index_1: str
):
"""Validate the inputs to the functionCallTimeLocks method."""
self.validator.assert_valid(
method_name="functionCallTimeLocks",
parameter_name="index_0",
argument_value=index_0,
)
self.validator.assert_valid(
method_name="functionCallTimeLocks",
parameter_name="index_1",
argument_value=index_1,
)
index_1 = self.validate_and_checksum_address(index_1)
return (index_0, index_1)
def call(
self,
index_0: Union[bytes, str],
index_1: str,
tx_params: Optional[TxParams] = None,
) -> Tuple[bool, int]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0, index_1).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
)
def estimate_gas(
self,
index_0: Union[bytes, str],
index_1: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0, index_1).estimateGas(
tx_params.as_dict()
)
class GetConfirmationCountMethod(ContractMethod):
"""Various interfaces to the getConfirmationCount method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, transaction_id: int):
"""Validate the inputs to the getConfirmationCount method."""
self.validator.assert_valid(
method_name="getConfirmationCount",
parameter_name="transactionId",
argument_value=transaction_id,
)
# safeguard against fractional inputs
transaction_id = int(transaction_id)
return transaction_id
def call(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
Returns number of confirmations of a transaction.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
:returns: Number of confirmations.
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(transaction_id).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).estimateGas(
tx_params.as_dict()
)
class GetConfirmationsMethod(ContractMethod):
"""Various interfaces to the getConfirmations method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, transaction_id: int):
"""Validate the inputs to the getConfirmations method."""
self.validator.assert_valid(
method_name="getConfirmations",
parameter_name="transactionId",
argument_value=transaction_id,
)
# safeguard against fractional inputs
transaction_id = int(transaction_id)
return transaction_id
def call(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> List[str]:
"""Execute underlying contract method via eth_call.
Returns array with owner addresses, which confirmed transaction.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
:returns: Returns array of owner addresses.
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(transaction_id).call(
tx_params.as_dict()
)
return [str(element) for element in returned]
def estimate_gas(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).estimateGas(
tx_params.as_dict()
)
class GetOwnersMethod(ContractMethod):
"""Various interfaces to the getOwners method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Returns list of owners.
:param tx_params: transaction parameters
:returns: List of owner addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetTransactionCountMethod(ContractMethod):
"""Various interfaces to the getTransactionCount method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, pending: bool, executed: bool):
"""Validate the inputs to the getTransactionCount method."""
self.validator.assert_valid(
method_name="getTransactionCount",
parameter_name="pending",
argument_value=pending,
)
self.validator.assert_valid(
method_name="getTransactionCount",
parameter_name="executed",
argument_value=executed,
)
return (pending, executed)
def call(
self,
pending: bool,
executed: bool,
tx_params: Optional[TxParams] = None,
) -> int:
"""Execute underlying contract method via eth_call.
Returns total number of transactions after filers are applied.
:param executed: Include executed transactions.
:param pending: Include pending transactions.
:param tx_params: transaction parameters
:returns: Total number of transactions after filters are applied.
"""
(pending, executed) = self.validate_and_normalize_inputs(
pending, executed
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(pending, executed).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self,
pending: bool,
executed: bool,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(pending, executed) = self.validate_and_normalize_inputs(
pending, executed
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pending, executed).estimateGas(
tx_params.as_dict()
)
class GetTransactionIdsMethod(ContractMethod):
"""Various interfaces to the getTransactionIds method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _from: int, to: int, pending: bool, executed: bool
):
"""Validate the inputs to the getTransactionIds method."""
self.validator.assert_valid(
method_name="getTransactionIds",
parameter_name="from",
argument_value=_from,
)
# safeguard against fractional inputs
_from = int(_from)
self.validator.assert_valid(
method_name="getTransactionIds",
parameter_name="to",
argument_value=to,
)
# safeguard against fractional inputs
to = int(to)
self.validator.assert_valid(
method_name="getTransactionIds",
parameter_name="pending",
argument_value=pending,
)
self.validator.assert_valid(
method_name="getTransactionIds",
parameter_name="executed",
argument_value=executed,
)
return (_from, to, pending, executed)
def call(
self,
_from: int,
to: int,
pending: bool,
executed: bool,
tx_params: Optional[TxParams] = None,
) -> List[int]:
"""Execute underlying contract method via eth_call.
Returns list of transaction IDs in defined range.
:param executed: Include executed transactions.
:param from: Index start position of transaction array.
:param pending: Include pending transactions.
:param to: Index end position of transaction array.
:param tx_params: transaction parameters
:returns: Returns array of transaction IDs.
"""
(_from, to, pending, executed) = self.validate_and_normalize_inputs(
_from, to, pending, executed
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_from, to, pending, executed).call(
tx_params.as_dict()
)
return [int(element) for element in returned]
def estimate_gas(
self,
_from: int,
to: int,
pending: bool,
executed: bool,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, to, pending, executed) = self.validate_and_normalize_inputs(
_from, to, pending, executed
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, to, pending, executed
).estimateGas(tx_params.as_dict())
class IsConfirmedMethod(ContractMethod):
"""Various interfaces to the isConfirmed method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, transaction_id: int):
"""Validate the inputs to the isConfirmed method."""
self.validator.assert_valid(
method_name="isConfirmed",
parameter_name="transactionId",
argument_value=transaction_id,
)
# safeguard against fractional inputs
transaction_id = int(transaction_id)
return transaction_id
def call(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
Returns the confirmation status of a transaction.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
:returns: Confirmation status.
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(transaction_id).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).estimateGas(
tx_params.as_dict()
)
class IsOwnerMethod(ContractMethod):
"""Various interfaces to the isOwner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the isOwner method."""
self.validator.assert_valid(
method_name="isOwner",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class OwnersMethod(ContractMethod):
"""Various interfaces to the owners method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the owners method."""
self.validator.assert_valid(
method_name="owners",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class RegisterFunctionCallMethod(ContractMethod):
"""Various interfaces to the registerFunctionCall method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
has_custom_time_lock: bool,
function_selector: Union[bytes, str],
destination: str,
new_seconds_time_locked: int,
):
"""Validate the inputs to the registerFunctionCall method."""
self.validator.assert_valid(
method_name="registerFunctionCall",
parameter_name="hasCustomTimeLock",
argument_value=has_custom_time_lock,
)
self.validator.assert_valid(
method_name="registerFunctionCall",
parameter_name="functionSelector",
argument_value=function_selector,
)
self.validator.assert_valid(
method_name="registerFunctionCall",
parameter_name="destination",
argument_value=destination,
)
destination = self.validate_and_checksum_address(destination)
self.validator.assert_valid(
method_name="registerFunctionCall",
parameter_name="newSecondsTimeLocked",
argument_value=new_seconds_time_locked,
)
return (
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
)
def call(
self,
has_custom_time_lock: bool,
function_selector: Union[bytes, str],
destination: str,
new_seconds_time_locked: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Registers a custom timelock to a specific function selector /
destination combo
:param destination: Address of destination where function will be
called.
:param functionSelector: 4 byte selector of registered function.
:param hasCustomTimeLock: True if timelock is custom.
:param newSecondsTimeLocked: Duration in seconds needed after a
transaction is confirmed to become executable.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
) = self.validate_and_normalize_inputs(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
).call(tx_params.as_dict())
def send_transaction(
self,
has_custom_time_lock: bool,
function_selector: Union[bytes, str],
destination: str,
new_seconds_time_locked: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Registers a custom timelock to a specific function selector /
destination combo
:param destination: Address of destination where function will be
called.
:param functionSelector: 4 byte selector of registered function.
:param hasCustomTimeLock: True if timelock is custom.
:param newSecondsTimeLocked: Duration in seconds needed after a
transaction is confirmed to become executable.
:param tx_params: transaction parameters
"""
(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
) = self.validate_and_normalize_inputs(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
).transact(tx_params.as_dict())
def build_transaction(
self,
has_custom_time_lock: bool,
function_selector: Union[bytes, str],
destination: str,
new_seconds_time_locked: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
) = self.validate_and_normalize_inputs(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
has_custom_time_lock: bool,
function_selector: Union[bytes, str],
destination: str,
new_seconds_time_locked: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
) = self.validate_and_normalize_inputs(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
has_custom_time_lock,
function_selector,
destination,
new_seconds_time_locked,
).estimateGas(tx_params.as_dict())
class RemoveOwnerMethod(ContractMethod):
"""Various interfaces to the removeOwner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, owner: str):
"""Validate the inputs to the removeOwner method."""
self.validator.assert_valid(
method_name="removeOwner",
parameter_name="owner",
argument_value=owner,
)
owner = self.validate_and_checksum_address(owner)
return owner
def call(self, owner: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Allows to remove an owner. Transaction has to be sent by wallet.
:param owner: Address of owner.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(owner) = self.validate_and_normalize_inputs(owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(owner).call(tx_params.as_dict())
def send_transaction(
self, owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows to remove an owner. Transaction has to be sent by wallet.
:param owner: Address of owner.
:param tx_params: transaction parameters
"""
(owner) = self.validate_and_normalize_inputs(owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner).transact(tx_params.as_dict())
def build_transaction(
self, owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(owner) = self.validate_and_normalize_inputs(owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(owner) = self.validate_and_normalize_inputs(owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner).estimateGas(tx_params.as_dict())
class ReplaceOwnerMethod(ContractMethod):
"""Various interfaces to the replaceOwner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, owner: str, new_owner: str):
"""Validate the inputs to the replaceOwner method."""
self.validator.assert_valid(
method_name="replaceOwner",
parameter_name="owner",
argument_value=owner,
)
owner = self.validate_and_checksum_address(owner)
self.validator.assert_valid(
method_name="replaceOwner",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return (owner, new_owner)
def call(
self, owner: str, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Allows to replace an owner with a new owner. Transaction has to be sent
by wallet.
:param newOwner: Address of new owner.
:param owner: Address of owner to be replaced.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(owner, new_owner) = self.validate_and_normalize_inputs(
owner, new_owner
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(owner, new_owner).call(tx_params.as_dict())
def send_transaction(
self, owner: str, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows to replace an owner with a new owner. Transaction has to be sent
by wallet.
:param newOwner: Address of new owner.
:param owner: Address of owner to be replaced.
:param tx_params: transaction parameters
"""
(owner, new_owner) = self.validate_and_normalize_inputs(
owner, new_owner
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner, new_owner).transact(
tx_params.as_dict()
)
def build_transaction(
self, owner: str, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(owner, new_owner) = self.validate_and_normalize_inputs(
owner, new_owner
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner, new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, owner: str, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(owner, new_owner) = self.validate_and_normalize_inputs(
owner, new_owner
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner, new_owner).estimateGas(
tx_params.as_dict()
)
class RequiredMethod(ContractMethod):
"""Various interfaces to the required method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RevokeConfirmationMethod(ContractMethod):
"""Various interfaces to the revokeConfirmation method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, transaction_id: int):
"""Validate the inputs to the revokeConfirmation method."""
self.validator.assert_valid(
method_name="revokeConfirmation",
parameter_name="transactionId",
argument_value=transaction_id,
)
# safeguard against fractional inputs
transaction_id = int(transaction_id)
return transaction_id
def call(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Allows an owner to revoke a confirmation for a transaction.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(transaction_id).call(tx_params.as_dict())
def send_transaction(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows an owner to revoke a confirmation for a transaction.
:param transactionId: Transaction ID.
:param tx_params: transaction parameters
"""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).transact(
tx_params.as_dict()
)
def build_transaction(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, transaction_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(transaction_id) = self.validate_and_normalize_inputs(transaction_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction_id).estimateGas(
tx_params.as_dict()
)
class SecondsTimeLockedMethod(ContractMethod):
"""Various interfaces to the secondsTimeLocked method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class SubmitTransactionMethod(ContractMethod):
"""Various interfaces to the submitTransaction method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, destination: str, value: int, data: Union[bytes, str]
):
"""Validate the inputs to the submitTransaction method."""
self.validator.assert_valid(
method_name="submitTransaction",
parameter_name="destination",
argument_value=destination,
)
destination = self.validate_and_checksum_address(destination)
self.validator.assert_valid(
method_name="submitTransaction",
parameter_name="value",
argument_value=value,
)
# safeguard against fractional inputs
value = int(value)
self.validator.assert_valid(
method_name="submitTransaction",
parameter_name="data",
argument_value=data,
)
return (destination, value, data)
def call(
self,
destination: str,
value: int,
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Execute underlying contract method via eth_call.
Allows an owner to submit and confirm a transaction.
:param data: Transaction data payload.
:param destination: Transaction target address.
:param value: Transaction ether value.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(destination, value, data) = self.validate_and_normalize_inputs(
destination, value, data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(destination, value, data).call(
tx_params.as_dict()
)
return int(returned)
def send_transaction(
self,
destination: str,
value: int,
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows an owner to submit and confirm a transaction.
:param data: Transaction data payload.
:param destination: Transaction target address.
:param value: Transaction ether value.
:param tx_params: transaction parameters
"""
(destination, value, data) = self.validate_and_normalize_inputs(
destination, value, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(destination, value, data).transact(
tx_params.as_dict()
)
def build_transaction(
self,
destination: str,
value: int,
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(destination, value, data) = self.validate_and_normalize_inputs(
destination, value, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
destination, value, data
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
destination: str,
value: int,
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(destination, value, data) = self.validate_and_normalize_inputs(
destination, value, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(destination, value, data).estimateGas(
tx_params.as_dict()
)
class TransactionCountMethod(ContractMethod):
"""Various interfaces to the transactionCount method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransactionsMethod(ContractMethod):
"""Various interfaces to the transactions method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the transactions method."""
self.validator.assert_valid(
method_name="transactions",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> Tuple[str, int, Union[bytes, str], bool]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
returned[3],
)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class AssetProxyOwner:
"""Wrapper class for AssetProxyOwner Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
max_owner_count: MaxOwnerCountMethod
"""Constructor-initialized instance of
:class:`MaxOwnerCountMethod`.
"""
add_owner: AddOwnerMethod
"""Constructor-initialized instance of
:class:`AddOwnerMethod`.
"""
change_requirement: ChangeRequirementMethod
"""Constructor-initialized instance of
:class:`ChangeRequirementMethod`.
"""
change_time_lock: ChangeTimeLockMethod
"""Constructor-initialized instance of
:class:`ChangeTimeLockMethod`.
"""
confirm_transaction: ConfirmTransactionMethod
"""Constructor-initialized instance of
:class:`ConfirmTransactionMethod`.
"""
confirmation_times: ConfirmationTimesMethod
"""Constructor-initialized instance of
:class:`ConfirmationTimesMethod`.
"""
confirmations: ConfirmationsMethod
"""Constructor-initialized instance of
:class:`ConfirmationsMethod`.
"""
execute_transaction: ExecuteTransactionMethod
"""Constructor-initialized instance of
:class:`ExecuteTransactionMethod`.
"""
function_call_time_locks: FunctionCallTimeLocksMethod
"""Constructor-initialized instance of
:class:`FunctionCallTimeLocksMethod`.
"""
get_confirmation_count: GetConfirmationCountMethod
"""Constructor-initialized instance of
:class:`GetConfirmationCountMethod`.
"""
get_confirmations: GetConfirmationsMethod
"""Constructor-initialized instance of
:class:`GetConfirmationsMethod`.
"""
get_owners: GetOwnersMethod
"""Constructor-initialized instance of
:class:`GetOwnersMethod`.
"""
get_transaction_count: GetTransactionCountMethod
"""Constructor-initialized instance of
:class:`GetTransactionCountMethod`.
"""
get_transaction_ids: GetTransactionIdsMethod
"""Constructor-initialized instance of
:class:`GetTransactionIdsMethod`.
"""
is_confirmed: IsConfirmedMethod
"""Constructor-initialized instance of
:class:`IsConfirmedMethod`.
"""
is_owner: IsOwnerMethod
"""Constructor-initialized instance of
:class:`IsOwnerMethod`.
"""
owners: OwnersMethod
"""Constructor-initialized instance of
:class:`OwnersMethod`.
"""
register_function_call: RegisterFunctionCallMethod
"""Constructor-initialized instance of
:class:`RegisterFunctionCallMethod`.
"""
remove_owner: RemoveOwnerMethod
"""Constructor-initialized instance of
:class:`RemoveOwnerMethod`.
"""
replace_owner: ReplaceOwnerMethod
"""Constructor-initialized instance of
:class:`ReplaceOwnerMethod`.
"""
required: RequiredMethod
"""Constructor-initialized instance of
:class:`RequiredMethod`.
"""
revoke_confirmation: RevokeConfirmationMethod
"""Constructor-initialized instance of
:class:`RevokeConfirmationMethod`.
"""
seconds_time_locked: SecondsTimeLockedMethod
"""Constructor-initialized instance of
:class:`SecondsTimeLockedMethod`.
"""
submit_transaction: SubmitTransactionMethod
"""Constructor-initialized instance of
:class:`SubmitTransactionMethod`.
"""
transaction_count: TransactionCountMethod
"""Constructor-initialized instance of
:class:`TransactionCountMethod`.
"""
transactions: TransactionsMethod
"""Constructor-initialized instance of
:class:`TransactionsMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: AssetProxyOwnerValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = AssetProxyOwnerValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=AssetProxyOwner.abi(),
).functions
self.max_owner_count = MaxOwnerCountMethod(
web3_or_provider, contract_address, functions.MAX_OWNER_COUNT
)
self.add_owner = AddOwnerMethod(
web3_or_provider, contract_address, functions.addOwner, validator
)
self.change_requirement = ChangeRequirementMethod(
web3_or_provider,
contract_address,
functions.changeRequirement,
validator,
)
self.change_time_lock = ChangeTimeLockMethod(
web3_or_provider,
contract_address,
functions.changeTimeLock,
validator,
)
self.confirm_transaction = ConfirmTransactionMethod(
web3_or_provider,
contract_address,
functions.confirmTransaction,
validator,
)
self.confirmation_times = ConfirmationTimesMethod(
web3_or_provider,
contract_address,
functions.confirmationTimes,
validator,
)
self.confirmations = ConfirmationsMethod(
web3_or_provider,
contract_address,
functions.confirmations,
validator,
)
self.execute_transaction = ExecuteTransactionMethod(
web3_or_provider,
contract_address,
functions.executeTransaction,
validator,
)
self.function_call_time_locks = FunctionCallTimeLocksMethod(
web3_or_provider,
contract_address,
functions.functionCallTimeLocks,
validator,
)
self.get_confirmation_count = GetConfirmationCountMethod(
web3_or_provider,
contract_address,
functions.getConfirmationCount,
validator,
)
self.get_confirmations = GetConfirmationsMethod(
web3_or_provider,
contract_address,
functions.getConfirmations,
validator,
)
self.get_owners = GetOwnersMethod(
web3_or_provider, contract_address, functions.getOwners
)
self.get_transaction_count = GetTransactionCountMethod(
web3_or_provider,
contract_address,
functions.getTransactionCount,
validator,
)
self.get_transaction_ids = GetTransactionIdsMethod(
web3_or_provider,
contract_address,
functions.getTransactionIds,
validator,
)
self.is_confirmed = IsConfirmedMethod(
web3_or_provider,
contract_address,
functions.isConfirmed,
validator,
)
self.is_owner = IsOwnerMethod(
web3_or_provider, contract_address, functions.isOwner, validator
)
self.owners = OwnersMethod(
web3_or_provider, contract_address, functions.owners, validator
)
self.register_function_call = RegisterFunctionCallMethod(
web3_or_provider,
contract_address,
functions.registerFunctionCall,
validator,
)
self.remove_owner = RemoveOwnerMethod(
web3_or_provider,
contract_address,
functions.removeOwner,
validator,
)
self.replace_owner = ReplaceOwnerMethod(
web3_or_provider,
contract_address,
functions.replaceOwner,
validator,
)
self.required = RequiredMethod(
web3_or_provider, contract_address, functions.required
)
self.revoke_confirmation = RevokeConfirmationMethod(
web3_or_provider,
contract_address,
functions.revokeConfirmation,
validator,
)
self.seconds_time_locked = SecondsTimeLockedMethod(
web3_or_provider, contract_address, functions.secondsTimeLocked
)
self.submit_transaction = SubmitTransactionMethod(
web3_or_provider,
contract_address,
functions.submitTransaction,
validator,
)
self.transaction_count = TransactionCountMethod(
web3_or_provider, contract_address, functions.transactionCount
)
self.transactions = TransactionsMethod(
web3_or_provider,
contract_address,
functions.transactions,
validator,
)
def get_confirmation_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Confirmation event.
:param tx_hash: hash of transaction emitting Confirmation event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.Confirmation()
.processReceipt(tx_receipt)
)
def get_confirmation_time_set_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ConfirmationTimeSet event.
:param tx_hash: hash of transaction emitting ConfirmationTimeSet event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.ConfirmationTimeSet()
.processReceipt(tx_receipt)
)
def get_deposit_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Deposit event.
:param tx_hash: hash of transaction emitting Deposit event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.Deposit()
.processReceipt(tx_receipt)
)
def get_execution_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Execution event.
:param tx_hash: hash of transaction emitting Execution event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.Execution()
.processReceipt(tx_receipt)
)
def get_execution_failure_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ExecutionFailure event.
:param tx_hash: hash of transaction emitting ExecutionFailure event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.ExecutionFailure()
.processReceipt(tx_receipt)
)
def get_function_call_time_lock_registration_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for FunctionCallTimeLockRegistration event.
:param tx_hash: hash of transaction emitting
FunctionCallTimeLockRegistration event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.FunctionCallTimeLockRegistration()
.processReceipt(tx_receipt)
)
def get_owner_addition_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for OwnerAddition event.
:param tx_hash: hash of transaction emitting OwnerAddition event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.OwnerAddition()
.processReceipt(tx_receipt)
)
def get_owner_removal_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for OwnerRemoval event.
:param tx_hash: hash of transaction emitting OwnerRemoval event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.OwnerRemoval()
.processReceipt(tx_receipt)
)
def get_requirement_change_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for RequirementChange event.
:param tx_hash: hash of transaction emitting RequirementChange event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.RequirementChange()
.processReceipt(tx_receipt)
)
def get_revocation_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Revocation event.
:param tx_hash: hash of transaction emitting Revocation event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.Revocation()
.processReceipt(tx_receipt)
)
def get_submission_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Submission event.
:param tx_hash: hash of transaction emitting Submission event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.Submission()
.processReceipt(tx_receipt)
)
def get_time_lock_change_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for TimeLockChange event.
:param tx_hash: hash of transaction emitting TimeLockChange event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=AssetProxyOwner.abi(),
)
.events.TimeLockChange()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"bytes4[]","name":"_functionSelectors","type":"bytes4[]"},{"internalType":"address[]","name":"_destinations","type":"address[]"},{"internalType":"uint128[]","name":"_functionCallTimeLockSeconds","type":"uint128[]"},{"internalType":"address[]","name":"_owners","type":"address[]"},{"internalType":"uint256","name":"_required","type":"uint256"},{"internalType":"uint256","name":"_defaultSecondsTimeLocked","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"Confirmation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"transactionId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"confirmationTime","type":"uint256"}],"name":"ConfirmationTimeSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"Execution","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"ExecutionFailure","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes4","name":"functionSelector","type":"bytes4"},{"indexed":false,"internalType":"address","name":"destination","type":"address"},{"indexed":false,"internalType":"bool","name":"hasCustomTimeLock","type":"bool"},{"indexed":false,"internalType":"uint128","name":"newSecondsTimeLocked","type":"uint128"}],"name":"FunctionCallTimeLockRegistration","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"OwnerAddition","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"OwnerRemoval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"required","type":"uint256"}],"name":"RequirementChange","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"Revocation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"Submission","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"secondsTimeLocked","type":"uint256"}],"name":"TimeLockChange","type":"event"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":true,"inputs":[],"name":"MAX_OWNER_COUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"addOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_required","type":"uint256"}],"name":"changeRequirement","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_secondsTimeLocked","type":"uint256"}],"name":"changeTimeLock","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"confirmTransaction","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"confirmationTimes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"},{"internalType":"address","name":"index_1","type":"address"}],"name":"confirmations","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"executeTransaction","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes4","name":"index_0","type":"bytes4"},{"internalType":"address","name":"index_1","type":"address"}],"name":"functionCallTimeLocks","outputs":[{"internalType":"bool","name":"hasCustomTimeLock","type":"bool"},{"internalType":"uint128","name":"secondsTimeLocked","type":"uint128"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"getConfirmationCount","outputs":[{"internalType":"uint256","name":"count","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"getConfirmations","outputs":[{"internalType":"address[]","name":"_confirmations","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwners","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bool","name":"pending","type":"bool"},{"internalType":"bool","name":"executed","type":"bool"}],"name":"getTransactionCount","outputs":[{"internalType":"uint256","name":"count","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"from","type":"uint256"},{"internalType":"uint256","name":"to","type":"uint256"},{"internalType":"bool","name":"pending","type":"bool"},{"internalType":"bool","name":"executed","type":"bool"}],"name":"getTransactionIds","outputs":[{"internalType":"uint256[]","name":"_transactionIds","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"isConfirmed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"isOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"owners","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bool","name":"hasCustomTimeLock","type":"bool"},{"internalType":"bytes4","name":"functionSelector","type":"bytes4"},{"internalType":"address","name":"destination","type":"address"},{"internalType":"uint128","name":"newSecondsTimeLocked","type":"uint128"}],"name":"registerFunctionCall","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"removeOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"newOwner","type":"address"}],"name":"replaceOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"required","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"revokeConfirmation","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"secondsTimeLocked","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"destination","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"submitTransaction","outputs":[{"internalType":"uint256","name":"transactionId","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"transactionCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"transactions","outputs":[{"internalType":"address","name":"destination","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"bool","name":"executed","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/asset_proxy_owner/__init__.py | __init__.py |
"""Conveniences for handling types representing Exchange Solidity structs.
The `TypedDict`:code: classes in the .exchange module represent tuples
encountered in the Exchange contract's ABI. However, they have weird names,
containing hashes of the tuple's field names, because the name of a Solidity
`struct`:code: isn't conveyed through the ABI. This module provides type
aliases with human-friendly names.
"""
from enum import auto, Enum
from . import (
LibFillResultsFillResults,
LibOrderOrder,
LibFillResultsMatchedFillResults,
LibZeroExTransactionZeroExTransaction,
LibOrderOrderInfo,
)
# Would rather not repeat ourselves below, but base classes are mentioned in
# the class docstrings because of a bug in sphinx rendering. Using the `..
# autoclass` directive, with the `:show-inheritance:` role, results in docs
# being rendered with just "Bases: dict", and no mention of the direct ancestor
# of each of these classes.
class FillResults(LibFillResultsFillResults):
"""The `FillResults`:code: Solidity struct.
Also known as
`zero_ex.contract_wrappers.exchange.LibFillResultsFillResults`:py:class:.
"""
class Order(LibOrderOrder):
"""The `Order`:code: Solidity struct.
Also known as
`zero_ex.contract_wrappers.exchange.LibOrderOrder`:py:class:.
"""
class MatchedFillResults(LibFillResultsMatchedFillResults):
"""The `MatchedFillResults`:code: Solidity struct.
Also known as
`zero_ex.contract_wrappers.exchange.LibFillResultsMatchedFillResults`:py:class:.
"""
class ZeroExTransaction(LibZeroExTransactionZeroExTransaction):
"""The `ZeroExTransaction`:code: Solidity struct.
Also known as
`zero_ex.contract_wrappers.exchange.LibZeroExTransactionZeroExTransaction`:py:class:.
"""
class OrderInfo(LibOrderOrderInfo):
"""The `OrderInfo`:code: Solidity struct.
Also known as
`zero_ex.contract_wrappers.exchange.LibOrderOrderInfo`:py:class:.
"""
class OrderStatus(Enum): # noqa: D101 # pylint: disable=missing-docstring
INVALID = 0
INVALID_MAKER_ASSET_AMOUNT = auto()
INVALID_TAKER_ASSET_AMOUNT = auto()
FILLABLE = auto()
EXPIRED = auto()
FULLY_FILLED = auto()
CANCELLED = auto()
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/exchange/types.py | types.py |
"""Web3.py-compatible middleware to be injected upon contract instantiation."""
from zero_ex.contract_wrappers.exceptions import (
exception_class_from_rich_revert_selector,
NoExceptionForSelector,
)
from . import exceptions
def rich_revert_handler(make_request, _):
"""Return a middlware to raise exceptions for rich revert return data."""
# noqa: D202 (No blank lines allowed after function docstring
def middleware(method, params):
response = make_request(method, params)
try:
raise exception_class_from_rich_revert_selector(
response["result"][0:10], exceptions
)(response["result"])
except NoExceptionForSelector:
# response prefix didn't indicate a known error
pass
except TypeError:
# eg "unhashable type: 'slice'". if response["result"] isn't
# sliceable (eg if it's a dict), then it definitely isn't a rich
# revert.
pass
except KeyError:
# response doesn't have a "result" key
pass
return response
return middleware
MIDDLEWARE = [{"layer": 0, "function": rich_revert_handler}]
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/exchange/middleware.py | middleware.py |
"""Validate inputs to the Exchange contract."""
from typing import Any, Union
from web3 import Web3
from web3.providers.base import BaseProvider
from zero_ex import json_schemas
from zero_ex.contract_wrappers.order_conversions import order_to_jsdict
from ..bases import Validator
class ExchangeValidator(Validator):
"""Validate inputs to Exchange methods."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
):
"""Initialize the class."""
super().__init__(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
if web3 is None:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
self.contract_address = contract_address
self.chain_id = web3.eth.chainId
def assert_valid(
self, method_name: str, parameter_name: str, argument_value: Any
) -> None:
"""Raise an exception if method input is not valid.
:param method_name: Name of the method whose input is to be validated.
:param parameter_name: Name of the parameter whose input is to be
validated.
:param argument_value: Value of argument to parameter to be validated.
"""
if parameter_name == "order":
json_schemas.assert_valid(
order_to_jsdict(
argument_value, self.chain_id, self.contract_address
),
"/orderSchema",
)
if parameter_name == "orders":
for order in argument_value:
json_schemas.assert_valid(
order_to_jsdict(
order, self.chain_id, self.contract_address
),
"/orderSchema",
)
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/exchange/validator.py | validator.py |
"""Generated wrapper for Exchange Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for Exchange below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ExchangeValidator,
)
except ImportError:
class ExchangeValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class LibFillResultsFillResults(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerAssetFilledAmount: int
takerAssetFilledAmount: int
makerFeePaid: int
takerFeePaid: int
protocolFeePaid: int
class LibFillResultsBatchMatchedFillResults(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
left: List[LibFillResultsFillResults]
right: List[LibFillResultsFillResults]
profitInLeftMakerAsset: int
profitInRightMakerAsset: int
class LibFillResultsMatchedFillResults(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
left: LibFillResultsFillResults
right: LibFillResultsFillResults
profitInLeftMakerAsset: int
profitInRightMakerAsset: int
class LibOrderOrder(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerAddress: str
takerAddress: str
feeRecipientAddress: str
senderAddress: str
makerAssetAmount: int
takerAssetAmount: int
makerFee: int
takerFee: int
expirationTimeSeconds: int
salt: int
makerAssetData: Union[bytes, str]
takerAssetData: Union[bytes, str]
makerFeeAssetData: Union[bytes, str]
takerFeeAssetData: Union[bytes, str]
class LibZeroExTransactionZeroExTransaction(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
salt: int
expirationTimeSeconds: int
gasPrice: int
signerAddress: str
data: Union[bytes, str]
class LibOrderOrderInfo(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
orderStatus: int
orderHash: Union[bytes, str]
orderTakerAssetFilledAmount: int
class Eip1271MagicValueMethod(ContractMethod):
"""Various interfaces to the EIP1271_MAGIC_VALUE method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class Eip712ExchangeDomainHashMethod(ContractMethod):
"""Various interfaces to the EIP712_EXCHANGE_DOMAIN_HASH method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AllowedValidatorsMethod(ContractMethod):
"""Various interfaces to the allowedValidators method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str, index_1: str):
"""Validate the inputs to the allowedValidators method."""
self.validator.assert_valid(
method_name="allowedValidators",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
self.validator.assert_valid(
method_name="allowedValidators",
parameter_name="index_1",
argument_value=index_1,
)
index_1 = self.validate_and_checksum_address(index_1)
return (index_0, index_1)
def call(
self, index_0: str, index_1: str, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0, index_1).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self, index_0: str, index_1: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0, index_1).estimateGas(
tx_params.as_dict()
)
class BatchCancelOrdersMethod(ContractMethod):
"""Various interfaces to the batchCancelOrders method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, orders: List[LibOrderOrder]):
"""Validate the inputs to the batchCancelOrders method."""
self.validator.assert_valid(
method_name="batchCancelOrders",
parameter_name="orders",
argument_value=orders,
)
return orders
def call(
self, orders: List[LibOrderOrder], tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Executes multiple calls of cancelOrder.
:param orders: Array of order specifications.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(orders) = self.validate_and_normalize_inputs(orders)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(orders).call(tx_params.as_dict())
def send_transaction(
self, orders: List[LibOrderOrder], tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes multiple calls of cancelOrder.
:param orders: Array of order specifications.
:param tx_params: transaction parameters
"""
(orders) = self.validate_and_normalize_inputs(orders)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(orders).transact(tx_params.as_dict())
def build_transaction(
self, orders: List[LibOrderOrder], tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(orders) = self.validate_and_normalize_inputs(orders)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(orders).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, orders: List[LibOrderOrder], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(orders) = self.validate_and_normalize_inputs(orders)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(orders).estimateGas(tx_params.as_dict())
class BatchExecuteTransactionsMethod(ContractMethod):
"""Various interfaces to the batchExecuteTransactions method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
transactions: List[LibZeroExTransactionZeroExTransaction],
signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the batchExecuteTransactions method."""
self.validator.assert_valid(
method_name="batchExecuteTransactions",
parameter_name="transactions",
argument_value=transactions,
)
self.validator.assert_valid(
method_name="batchExecuteTransactions",
parameter_name="signatures",
argument_value=signatures,
)
return (transactions, signatures)
def call(
self,
transactions: List[LibZeroExTransactionZeroExTransaction],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> List[Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Executes a batch of Exchange method calls in the context of signer(s).
:param signatures: Array of proofs that transactions have been signed
by signer(s).
:param transactions: Array of 0x transaction structures.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(transactions, signatures) = self.validate_and_normalize_inputs(
transactions, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(transactions, signatures).call(
tx_params.as_dict()
)
return [Union[bytes, str](element) for element in returned]
def send_transaction(
self,
transactions: List[LibZeroExTransactionZeroExTransaction],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes a batch of Exchange method calls in the context of signer(s).
:param signatures: Array of proofs that transactions have been signed
by signer(s).
:param transactions: Array of 0x transaction structures.
:param tx_params: transaction parameters
"""
(transactions, signatures) = self.validate_and_normalize_inputs(
transactions, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transactions, signatures).transact(
tx_params.as_dict()
)
def build_transaction(
self,
transactions: List[LibZeroExTransactionZeroExTransaction],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(transactions, signatures) = self.validate_and_normalize_inputs(
transactions, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
transactions, signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
transactions: List[LibZeroExTransactionZeroExTransaction],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(transactions, signatures) = self.validate_and_normalize_inputs(
transactions, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transactions, signatures).estimateGas(
tx_params.as_dict()
)
class BatchFillOrKillOrdersMethod(ContractMethod):
"""Various interfaces to the batchFillOrKillOrders method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the batchFillOrKillOrders method."""
self.validator.assert_valid(
method_name="batchFillOrKillOrders",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="batchFillOrKillOrders",
parameter_name="takerAssetFillAmounts",
argument_value=taker_asset_fill_amounts,
)
self.validator.assert_valid(
method_name="batchFillOrKillOrders",
parameter_name="signatures",
argument_value=signatures,
)
return (orders, taker_asset_fill_amounts, signatures)
def call(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> List[LibFillResultsFillResults]:
"""Execute underlying contract method via eth_call.
Executes multiple calls of fillOrKillOrder.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been created by makers.
:param takerAssetFillAmounts: Array of desired amounts of takerAsset to
sell in orders.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).call(tx_params.as_dict())
return [
LibFillResultsFillResults(
makerAssetFilledAmount=element[0],
takerAssetFilledAmount=element[1],
makerFeePaid=element[2],
takerFeePaid=element[3],
protocolFeePaid=element[4],
)
for element in returned
]
def send_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes multiple calls of fillOrKillOrder.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been created by makers.
:param takerAssetFillAmounts: Array of desired amounts of takerAsset to
sell in orders.
:param tx_params: transaction parameters
"""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).estimateGas(tx_params.as_dict())
class BatchFillOrdersMethod(ContractMethod):
"""Various interfaces to the batchFillOrders method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the batchFillOrders method."""
self.validator.assert_valid(
method_name="batchFillOrders",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="batchFillOrders",
parameter_name="takerAssetFillAmounts",
argument_value=taker_asset_fill_amounts,
)
self.validator.assert_valid(
method_name="batchFillOrders",
parameter_name="signatures",
argument_value=signatures,
)
return (orders, taker_asset_fill_amounts, signatures)
def call(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> List[LibFillResultsFillResults]:
"""Execute underlying contract method via eth_call.
Executes multiple calls of fillOrder.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been created by makers.
:param takerAssetFillAmounts: Array of desired amounts of takerAsset to
sell in orders.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).call(tx_params.as_dict())
return [
LibFillResultsFillResults(
makerAssetFilledAmount=element[0],
takerAssetFilledAmount=element[1],
makerFeePaid=element[2],
takerFeePaid=element[3],
protocolFeePaid=element[4],
)
for element in returned
]
def send_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes multiple calls of fillOrder.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been created by makers.
:param takerAssetFillAmounts: Array of desired amounts of takerAsset to
sell in orders.
:param tx_params: transaction parameters
"""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).estimateGas(tx_params.as_dict())
class BatchFillOrdersNoThrowMethod(ContractMethod):
"""Various interfaces to the batchFillOrdersNoThrow method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the batchFillOrdersNoThrow method."""
self.validator.assert_valid(
method_name="batchFillOrdersNoThrow",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="batchFillOrdersNoThrow",
parameter_name="takerAssetFillAmounts",
argument_value=taker_asset_fill_amounts,
)
self.validator.assert_valid(
method_name="batchFillOrdersNoThrow",
parameter_name="signatures",
argument_value=signatures,
)
return (orders, taker_asset_fill_amounts, signatures)
def call(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> List[LibFillResultsFillResults]:
"""Execute underlying contract method via eth_call.
Executes multiple calls of fillOrder. If any fill reverts, the error is
caught and ignored.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been created by makers.
:param takerAssetFillAmounts: Array of desired amounts of takerAsset to
sell in orders.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).call(tx_params.as_dict())
return [
LibFillResultsFillResults(
makerAssetFilledAmount=element[0],
takerAssetFilledAmount=element[1],
makerFeePaid=element[2],
takerFeePaid=element[3],
protocolFeePaid=element[4],
)
for element in returned
]
def send_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes multiple calls of fillOrder. If any fill reverts, the error is
caught and ignored.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been created by makers.
:param takerAssetFillAmounts: Array of desired amounts of takerAsset to
sell in orders.
:param tx_params: transaction parameters
"""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amounts: List[int],
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
taker_asset_fill_amounts,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amounts, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amounts, signatures
).estimateGas(tx_params.as_dict())
class BatchMatchOrdersMethod(ContractMethod):
"""Various interfaces to the batchMatchOrders method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the batchMatchOrders method."""
self.validator.assert_valid(
method_name="batchMatchOrders",
parameter_name="leftOrders",
argument_value=left_orders,
)
self.validator.assert_valid(
method_name="batchMatchOrders",
parameter_name="rightOrders",
argument_value=right_orders,
)
self.validator.assert_valid(
method_name="batchMatchOrders",
parameter_name="leftSignatures",
argument_value=left_signatures,
)
self.validator.assert_valid(
method_name="batchMatchOrders",
parameter_name="rightSignatures",
argument_value=right_signatures,
)
return (left_orders, right_orders, left_signatures, right_signatures)
def call(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsBatchMatchedFillResults:
"""Execute underlying contract method via eth_call.
Match complementary orders that have a profitable spread. Each order is
filled at their respective price point, and the matcher receives a
profit denominated in the left maker asset.
:param leftOrders: Set of orders with the same maker / taker asset.
:param leftSignatures: Proof that left orders were created by the left
makers.
:param rightOrders: Set of orders to match against `leftOrders`
:param rightSignatures: Proof that right orders were created by the
right makers.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
left_orders,
right_orders,
left_signatures,
right_signatures,
) = self.validate_and_normalize_inputs(
left_orders, right_orders, left_signatures, right_signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
left_orders, right_orders, left_signatures, right_signatures
).call(tx_params.as_dict())
return LibFillResultsBatchMatchedFillResults(
left=returned[0],
right=returned[1],
profitInLeftMakerAsset=returned[2],
profitInRightMakerAsset=returned[3],
)
def send_transaction(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Match complementary orders that have a profitable spread. Each order is
filled at their respective price point, and the matcher receives a
profit denominated in the left maker asset.
:param leftOrders: Set of orders with the same maker / taker asset.
:param leftSignatures: Proof that left orders were created by the left
makers.
:param rightOrders: Set of orders to match against `leftOrders`
:param rightSignatures: Proof that right orders were created by the
right makers.
:param tx_params: transaction parameters
"""
(
left_orders,
right_orders,
left_signatures,
right_signatures,
) = self.validate_and_normalize_inputs(
left_orders, right_orders, left_signatures, right_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_orders, right_orders, left_signatures, right_signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
left_orders,
right_orders,
left_signatures,
right_signatures,
) = self.validate_and_normalize_inputs(
left_orders, right_orders, left_signatures, right_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_orders, right_orders, left_signatures, right_signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
left_orders,
right_orders,
left_signatures,
right_signatures,
) = self.validate_and_normalize_inputs(
left_orders, right_orders, left_signatures, right_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_orders, right_orders, left_signatures, right_signatures
).estimateGas(tx_params.as_dict())
class BatchMatchOrdersWithMaximalFillMethod(ContractMethod):
"""Various interfaces to the batchMatchOrdersWithMaximalFill method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the batchMatchOrdersWithMaximalFill method."""
self.validator.assert_valid(
method_name="batchMatchOrdersWithMaximalFill",
parameter_name="leftOrders",
argument_value=left_orders,
)
self.validator.assert_valid(
method_name="batchMatchOrdersWithMaximalFill",
parameter_name="rightOrders",
argument_value=right_orders,
)
self.validator.assert_valid(
method_name="batchMatchOrdersWithMaximalFill",
parameter_name="leftSignatures",
argument_value=left_signatures,
)
self.validator.assert_valid(
method_name="batchMatchOrdersWithMaximalFill",
parameter_name="rightSignatures",
argument_value=right_signatures,
)
return (left_orders, right_orders, left_signatures, right_signatures)
def call(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsBatchMatchedFillResults:
"""Execute underlying contract method via eth_call.
Match complementary orders that have a profitable spread. Each order is
maximally filled at their respective price point, and the matcher
receives a profit denominated in either the left maker asset, right
maker asset, or a combination of both.
:param leftOrders: Set of orders with the same maker / taker asset.
:param leftSignatures: Proof that left orders were created by the left
makers.
:param rightOrders: Set of orders to match against `leftOrders`
:param rightSignatures: Proof that right orders were created by the
right makers.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
left_orders,
right_orders,
left_signatures,
right_signatures,
) = self.validate_and_normalize_inputs(
left_orders, right_orders, left_signatures, right_signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
left_orders, right_orders, left_signatures, right_signatures
).call(tx_params.as_dict())
return LibFillResultsBatchMatchedFillResults(
left=returned[0],
right=returned[1],
profitInLeftMakerAsset=returned[2],
profitInRightMakerAsset=returned[3],
)
def send_transaction(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Match complementary orders that have a profitable spread. Each order is
maximally filled at their respective price point, and the matcher
receives a profit denominated in either the left maker asset, right
maker asset, or a combination of both.
:param leftOrders: Set of orders with the same maker / taker asset.
:param leftSignatures: Proof that left orders were created by the left
makers.
:param rightOrders: Set of orders to match against `leftOrders`
:param rightSignatures: Proof that right orders were created by the
right makers.
:param tx_params: transaction parameters
"""
(
left_orders,
right_orders,
left_signatures,
right_signatures,
) = self.validate_and_normalize_inputs(
left_orders, right_orders, left_signatures, right_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_orders, right_orders, left_signatures, right_signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
left_orders,
right_orders,
left_signatures,
right_signatures,
) = self.validate_and_normalize_inputs(
left_orders, right_orders, left_signatures, right_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_orders, right_orders, left_signatures, right_signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
left_orders: List[LibOrderOrder],
right_orders: List[LibOrderOrder],
left_signatures: List[Union[bytes, str]],
right_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
left_orders,
right_orders,
left_signatures,
right_signatures,
) = self.validate_and_normalize_inputs(
left_orders, right_orders, left_signatures, right_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_orders, right_orders, left_signatures, right_signatures
).estimateGas(tx_params.as_dict())
class CancelOrderMethod(ContractMethod):
"""Various interfaces to the cancelOrder method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, order: LibOrderOrder):
"""Validate the inputs to the cancelOrder method."""
self.validator.assert_valid(
method_name="cancelOrder",
parameter_name="order",
argument_value=order,
)
return order
def call(
self, order: LibOrderOrder, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
After calling, the order can not be filled anymore.
:param order: Order struct containing order specifications.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(order).call(tx_params.as_dict())
def send_transaction(
self, order: LibOrderOrder, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
After calling, the order can not be filled anymore.
:param order: Order struct containing order specifications.
:param tx_params: transaction parameters
"""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order).transact(tx_params.as_dict())
def build_transaction(
self, order: LibOrderOrder, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, order: LibOrderOrder, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order).estimateGas(tx_params.as_dict())
class CancelOrdersUpToMethod(ContractMethod):
"""Various interfaces to the cancelOrdersUpTo method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target_order_epoch: int):
"""Validate the inputs to the cancelOrdersUpTo method."""
self.validator.assert_valid(
method_name="cancelOrdersUpTo",
parameter_name="targetOrderEpoch",
argument_value=target_order_epoch,
)
# safeguard against fractional inputs
target_order_epoch = int(target_order_epoch)
return target_order_epoch
def call(
self, target_order_epoch: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Cancels all orders created by makerAddress with a salt less than or
equal to the targetOrderEpoch and senderAddress equal to msg.sender (or
null address if msg.sender == makerAddress).
:param targetOrderEpoch: Orders created with a salt less or equal to
this value will be cancelled.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target_order_epoch) = self.validate_and_normalize_inputs(
target_order_epoch
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target_order_epoch).call(tx_params.as_dict())
def send_transaction(
self, target_order_epoch: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Cancels all orders created by makerAddress with a salt less than or
equal to the targetOrderEpoch and senderAddress equal to msg.sender (or
null address if msg.sender == makerAddress).
:param targetOrderEpoch: Orders created with a salt less or equal to
this value will be cancelled.
:param tx_params: transaction parameters
"""
(target_order_epoch) = self.validate_and_normalize_inputs(
target_order_epoch
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target_order_epoch).transact(
tx_params.as_dict()
)
def build_transaction(
self, target_order_epoch: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target_order_epoch) = self.validate_and_normalize_inputs(
target_order_epoch
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target_order_epoch).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target_order_epoch: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target_order_epoch) = self.validate_and_normalize_inputs(
target_order_epoch
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target_order_epoch).estimateGas(
tx_params.as_dict()
)
class CancelledMethod(ContractMethod):
"""Various interfaces to the cancelled method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: Union[bytes, str]):
"""Validate the inputs to the cancelled method."""
self.validator.assert_valid(
method_name="cancelled",
parameter_name="index_0",
argument_value=index_0,
)
return index_0
def call(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class CurrentContextAddressMethod(ContractMethod):
"""Various interfaces to the currentContextAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class ExecuteTransactionMethod(ContractMethod):
"""Various interfaces to the executeTransaction method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
transaction: LibZeroExTransactionZeroExTransaction,
signature: Union[bytes, str],
):
"""Validate the inputs to the executeTransaction method."""
self.validator.assert_valid(
method_name="executeTransaction",
parameter_name="transaction",
argument_value=transaction,
)
self.validator.assert_valid(
method_name="executeTransaction",
parameter_name="signature",
argument_value=signature,
)
return (transaction, signature)
def call(
self,
transaction: LibZeroExTransactionZeroExTransaction,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Executes an Exchange method call in the context of signer.
:param signature: Proof that transaction has been signed by signer.
:param transaction: 0x transaction structure.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(transaction, signature) = self.validate_and_normalize_inputs(
transaction, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(transaction, signature).call(
tx_params.as_dict()
)
return Union[bytes, str](returned)
def send_transaction(
self,
transaction: LibZeroExTransactionZeroExTransaction,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes an Exchange method call in the context of signer.
:param signature: Proof that transaction has been signed by signer.
:param transaction: 0x transaction structure.
:param tx_params: transaction parameters
"""
(transaction, signature) = self.validate_and_normalize_inputs(
transaction, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction, signature).transact(
tx_params.as_dict()
)
def build_transaction(
self,
transaction: LibZeroExTransactionZeroExTransaction,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(transaction, signature) = self.validate_and_normalize_inputs(
transaction, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
transaction, signature
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
transaction: LibZeroExTransactionZeroExTransaction,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(transaction, signature) = self.validate_and_normalize_inputs(
transaction, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction, signature).estimateGas(
tx_params.as_dict()
)
class FillOrKillOrderMethod(ContractMethod):
"""Various interfaces to the fillOrKillOrder method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
):
"""Validate the inputs to the fillOrKillOrder method."""
self.validator.assert_valid(
method_name="fillOrKillOrder",
parameter_name="order",
argument_value=order,
)
self.validator.assert_valid(
method_name="fillOrKillOrder",
parameter_name="takerAssetFillAmount",
argument_value=taker_asset_fill_amount,
)
# safeguard against fractional inputs
taker_asset_fill_amount = int(taker_asset_fill_amount)
self.validator.assert_valid(
method_name="fillOrKillOrder",
parameter_name="signature",
argument_value=signature,
)
return (order, taker_asset_fill_amount, signature)
def call(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsFillResults:
"""Execute underlying contract method via eth_call.
Fills the input order. Reverts if exact takerAssetFillAmount not
filled.
:param order: Order struct containing order specifications.
:param signature: Proof that order has been created by maker.
:param takerAssetFillAmount: Desired amount of takerAsset to sell.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
order,
taker_asset_fill_amount,
signature,
) = self.validate_and_normalize_inputs(
order, taker_asset_fill_amount, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
order, taker_asset_fill_amount, signature
).call(tx_params.as_dict())
return LibFillResultsFillResults(
makerAssetFilledAmount=returned[0],
takerAssetFilledAmount=returned[1],
makerFeePaid=returned[2],
takerFeePaid=returned[3],
protocolFeePaid=returned[4],
)
def send_transaction(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Fills the input order. Reverts if exact takerAssetFillAmount not
filled.
:param order: Order struct containing order specifications.
:param signature: Proof that order has been created by maker.
:param takerAssetFillAmount: Desired amount of takerAsset to sell.
:param tx_params: transaction parameters
"""
(
order,
taker_asset_fill_amount,
signature,
) = self.validate_and_normalize_inputs(
order, taker_asset_fill_amount, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_asset_fill_amount, signature
).transact(tx_params.as_dict())
def build_transaction(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
order,
taker_asset_fill_amount,
signature,
) = self.validate_and_normalize_inputs(
order, taker_asset_fill_amount, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_asset_fill_amount, signature
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
order,
taker_asset_fill_amount,
signature,
) = self.validate_and_normalize_inputs(
order, taker_asset_fill_amount, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_asset_fill_amount, signature
).estimateGas(tx_params.as_dict())
class FillOrderMethod(ContractMethod):
"""Various interfaces to the fillOrder method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
):
"""Validate the inputs to the fillOrder method."""
self.validator.assert_valid(
method_name="fillOrder",
parameter_name="order",
argument_value=order,
)
self.validator.assert_valid(
method_name="fillOrder",
parameter_name="takerAssetFillAmount",
argument_value=taker_asset_fill_amount,
)
# safeguard against fractional inputs
taker_asset_fill_amount = int(taker_asset_fill_amount)
self.validator.assert_valid(
method_name="fillOrder",
parameter_name="signature",
argument_value=signature,
)
return (order, taker_asset_fill_amount, signature)
def call(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsFillResults:
"""Execute underlying contract method via eth_call.
Fills the input order.
:param order: Order struct containing order specifications.
:param signature: Proof that order has been created by maker.
:param takerAssetFillAmount: Desired amount of takerAsset to sell.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
order,
taker_asset_fill_amount,
signature,
) = self.validate_and_normalize_inputs(
order, taker_asset_fill_amount, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
order, taker_asset_fill_amount, signature
).call(tx_params.as_dict())
return LibFillResultsFillResults(
makerAssetFilledAmount=returned[0],
takerAssetFilledAmount=returned[1],
makerFeePaid=returned[2],
takerFeePaid=returned[3],
protocolFeePaid=returned[4],
)
def send_transaction(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Fills the input order.
:param order: Order struct containing order specifications.
:param signature: Proof that order has been created by maker.
:param takerAssetFillAmount: Desired amount of takerAsset to sell.
:param tx_params: transaction parameters
"""
(
order,
taker_asset_fill_amount,
signature,
) = self.validate_and_normalize_inputs(
order, taker_asset_fill_amount, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_asset_fill_amount, signature
).transact(tx_params.as_dict())
def build_transaction(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
order,
taker_asset_fill_amount,
signature,
) = self.validate_and_normalize_inputs(
order, taker_asset_fill_amount, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_asset_fill_amount, signature
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
order: LibOrderOrder,
taker_asset_fill_amount: int,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
order,
taker_asset_fill_amount,
signature,
) = self.validate_and_normalize_inputs(
order, taker_asset_fill_amount, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
order, taker_asset_fill_amount, signature
).estimateGas(tx_params.as_dict())
class FilledMethod(ContractMethod):
"""Various interfaces to the filled method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: Union[bytes, str]):
"""Validate the inputs to the filled method."""
self.validator.assert_valid(
method_name="filled",
parameter_name="index_0",
argument_value=index_0,
)
return index_0
def call(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class GetAssetProxyMethod(ContractMethod):
"""Various interfaces to the getAssetProxy method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_proxy_id: Union[bytes, str]):
"""Validate the inputs to the getAssetProxy method."""
self.validator.assert_valid(
method_name="getAssetProxy",
parameter_name="assetProxyId",
argument_value=asset_proxy_id,
)
return asset_proxy_id
def call(
self,
asset_proxy_id: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> str:
"""Execute underlying contract method via eth_call.
Gets an asset proxy.
:param assetProxyId: Id of the asset proxy.
:param tx_params: transaction parameters
:returns: The asset proxy registered to assetProxyId. Returns 0x0 if no
proxy is registered.
"""
(asset_proxy_id) = self.validate_and_normalize_inputs(asset_proxy_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_proxy_id).call(
tx_params.as_dict()
)
return str(returned)
def estimate_gas(
self,
asset_proxy_id: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_proxy_id) = self.validate_and_normalize_inputs(asset_proxy_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_proxy_id).estimateGas(
tx_params.as_dict()
)
class GetOrderInfoMethod(ContractMethod):
"""Various interfaces to the getOrderInfo method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, order: LibOrderOrder):
"""Validate the inputs to the getOrderInfo method."""
self.validator.assert_valid(
method_name="getOrderInfo",
parameter_name="order",
argument_value=order,
)
return order
def call(
self, order: LibOrderOrder, tx_params: Optional[TxParams] = None
) -> LibOrderOrderInfo:
"""Execute underlying contract method via eth_call.
Gets information about an order: status, hash, and amount filled.
:param order: Order to gather information on.
:param tx_params: transaction parameters
:returns: OrderInfo Information about the order and its state. See
LibOrder.OrderInfo for a complete description.
"""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(order).call(tx_params.as_dict())
return LibOrderOrderInfo(
orderStatus=returned[0],
orderHash=returned[1],
orderTakerAssetFilledAmount=returned[2],
)
def estimate_gas(
self, order: LibOrderOrder, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order).estimateGas(tx_params.as_dict())
class IsValidHashSignatureMethod(ContractMethod):
"""Various interfaces to the isValidHashSignature method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
_hash: Union[bytes, str],
signer_address: str,
signature: Union[bytes, str],
):
"""Validate the inputs to the isValidHashSignature method."""
self.validator.assert_valid(
method_name="isValidHashSignature",
parameter_name="hash",
argument_value=_hash,
)
self.validator.assert_valid(
method_name="isValidHashSignature",
parameter_name="signerAddress",
argument_value=signer_address,
)
signer_address = self.validate_and_checksum_address(signer_address)
self.validator.assert_valid(
method_name="isValidHashSignature",
parameter_name="signature",
argument_value=signature,
)
return (_hash, signer_address, signature)
def call(
self,
_hash: Union[bytes, str],
signer_address: str,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> bool:
"""Execute underlying contract method via eth_call.
Verifies that a hash has been signed by the given signer.
:param hash: Any 32-byte hash.
:param signature: Proof that the hash has been signed by signer.
:param signerAddress: Address that should have signed the given hash.
:param tx_params: transaction parameters
:returns: isValid `true` if the signature is valid for the given hash
and signer.
"""
(
_hash,
signer_address,
signature,
) = self.validate_and_normalize_inputs(
_hash, signer_address, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
_hash, signer_address, signature
).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self,
_hash: Union[bytes, str],
signer_address: str,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
_hash,
signer_address,
signature,
) = self.validate_and_normalize_inputs(
_hash, signer_address, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_hash, signer_address, signature
).estimateGas(tx_params.as_dict())
class IsValidOrderSignatureMethod(ContractMethod):
"""Various interfaces to the isValidOrderSignature method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, order: LibOrderOrder, signature: Union[bytes, str]
):
"""Validate the inputs to the isValidOrderSignature method."""
self.validator.assert_valid(
method_name="isValidOrderSignature",
parameter_name="order",
argument_value=order,
)
self.validator.assert_valid(
method_name="isValidOrderSignature",
parameter_name="signature",
argument_value=signature,
)
return (order, signature)
def call(
self,
order: LibOrderOrder,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> bool:
"""Execute underlying contract method via eth_call.
Verifies that a signature for an order is valid.
:param order: The order.
:param signature: Proof that the order has been signed by signer.
:param tx_params: transaction parameters
:returns: isValid `true` if the signature is valid for the given order
and signer.
"""
(order, signature) = self.validate_and_normalize_inputs(
order, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(order, signature).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self,
order: LibOrderOrder,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(order, signature) = self.validate_and_normalize_inputs(
order, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order, signature).estimateGas(
tx_params.as_dict()
)
class IsValidTransactionSignatureMethod(ContractMethod):
"""Various interfaces to the isValidTransactionSignature method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
transaction: LibZeroExTransactionZeroExTransaction,
signature: Union[bytes, str],
):
"""Validate the inputs to the isValidTransactionSignature method."""
self.validator.assert_valid(
method_name="isValidTransactionSignature",
parameter_name="transaction",
argument_value=transaction,
)
self.validator.assert_valid(
method_name="isValidTransactionSignature",
parameter_name="signature",
argument_value=signature,
)
return (transaction, signature)
def call(
self,
transaction: LibZeroExTransactionZeroExTransaction,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> bool:
"""Execute underlying contract method via eth_call.
Verifies that a signature for a transaction is valid.
:param signature: Proof that the order has been signed by signer.
:param transaction: The transaction.
:param tx_params: transaction parameters
:returns: isValid `true` if the signature is valid for the given
transaction and signer.
"""
(transaction, signature) = self.validate_and_normalize_inputs(
transaction, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(transaction, signature).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self,
transaction: LibZeroExTransactionZeroExTransaction,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(transaction, signature) = self.validate_and_normalize_inputs(
transaction, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(transaction, signature).estimateGas(
tx_params.as_dict()
)
class MarketBuyOrdersFillOrKillMethod(ContractMethod):
"""Various interfaces to the marketBuyOrdersFillOrKill method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the marketBuyOrdersFillOrKill method."""
self.validator.assert_valid(
method_name="marketBuyOrdersFillOrKill",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="marketBuyOrdersFillOrKill",
parameter_name="makerAssetFillAmount",
argument_value=maker_asset_fill_amount,
)
# safeguard against fractional inputs
maker_asset_fill_amount = int(maker_asset_fill_amount)
self.validator.assert_valid(
method_name="marketBuyOrdersFillOrKill",
parameter_name="signatures",
argument_value=signatures,
)
return (orders, maker_asset_fill_amount, signatures)
def call(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsFillResults:
"""Execute underlying contract method via eth_call.
Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has
been bought. NOTE: This function does not enforce that the makerAsset
is the same for each order.
:param makerAssetFillAmount: Minimum amount of makerAsset to buy.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been signed by makers.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
maker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, maker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, maker_asset_fill_amount, signatures
).call(tx_params.as_dict())
return LibFillResultsFillResults(
makerAssetFilledAmount=returned[0],
takerAssetFilledAmount=returned[1],
makerFeePaid=returned[2],
takerFeePaid=returned[3],
protocolFeePaid=returned[4],
)
def send_transaction(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has
been bought. NOTE: This function does not enforce that the makerAsset
is the same for each order.
:param makerAssetFillAmount: Minimum amount of makerAsset to buy.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been signed by makers.
:param tx_params: transaction parameters
"""
(
orders,
maker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, maker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, maker_asset_fill_amount, signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
maker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, maker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, maker_asset_fill_amount, signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
maker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, maker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, maker_asset_fill_amount, signatures
).estimateGas(tx_params.as_dict())
class MarketBuyOrdersNoThrowMethod(ContractMethod):
"""Various interfaces to the marketBuyOrdersNoThrow method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the marketBuyOrdersNoThrow method."""
self.validator.assert_valid(
method_name="marketBuyOrdersNoThrow",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="marketBuyOrdersNoThrow",
parameter_name="makerAssetFillAmount",
argument_value=maker_asset_fill_amount,
)
# safeguard against fractional inputs
maker_asset_fill_amount = int(maker_asset_fill_amount)
self.validator.assert_valid(
method_name="marketBuyOrdersNoThrow",
parameter_name="signatures",
argument_value=signatures,
)
return (orders, maker_asset_fill_amount, signatures)
def call(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsFillResults:
"""Execute underlying contract method via eth_call.
Executes multiple calls of fillOrder until total amount of makerAsset
is bought by taker. If any fill reverts, the error is caught and
ignored. NOTE: This function does not enforce that the makerAsset is
the same for each order.
:param makerAssetFillAmount: Desired amount of makerAsset to buy.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been signed by makers.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
maker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, maker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, maker_asset_fill_amount, signatures
).call(tx_params.as_dict())
return LibFillResultsFillResults(
makerAssetFilledAmount=returned[0],
takerAssetFilledAmount=returned[1],
makerFeePaid=returned[2],
takerFeePaid=returned[3],
protocolFeePaid=returned[4],
)
def send_transaction(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes multiple calls of fillOrder until total amount of makerAsset
is bought by taker. If any fill reverts, the error is caught and
ignored. NOTE: This function does not enforce that the makerAsset is
the same for each order.
:param makerAssetFillAmount: Desired amount of makerAsset to buy.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been signed by makers.
:param tx_params: transaction parameters
"""
(
orders,
maker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, maker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, maker_asset_fill_amount, signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
maker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, maker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, maker_asset_fill_amount, signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
maker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
maker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, maker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, maker_asset_fill_amount, signatures
).estimateGas(tx_params.as_dict())
class MarketSellOrdersFillOrKillMethod(ContractMethod):
"""Various interfaces to the marketSellOrdersFillOrKill method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the marketSellOrdersFillOrKill method."""
self.validator.assert_valid(
method_name="marketSellOrdersFillOrKill",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="marketSellOrdersFillOrKill",
parameter_name="takerAssetFillAmount",
argument_value=taker_asset_fill_amount,
)
# safeguard against fractional inputs
taker_asset_fill_amount = int(taker_asset_fill_amount)
self.validator.assert_valid(
method_name="marketSellOrdersFillOrKill",
parameter_name="signatures",
argument_value=signatures,
)
return (orders, taker_asset_fill_amount, signatures)
def call(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsFillResults:
"""Execute underlying contract method via eth_call.
Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount
has been sold. NOTE: This function does not enforce that the takerAsset
is the same for each order.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been signed by makers.
:param takerAssetFillAmount: Minimum amount of takerAsset to sell.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
taker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, taker_asset_fill_amount, signatures
).call(tx_params.as_dict())
return LibFillResultsFillResults(
makerAssetFilledAmount=returned[0],
takerAssetFilledAmount=returned[1],
makerFeePaid=returned[2],
takerFeePaid=returned[3],
protocolFeePaid=returned[4],
)
def send_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount
has been sold. NOTE: This function does not enforce that the takerAsset
is the same for each order.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been signed by makers.
:param takerAssetFillAmount: Minimum amount of takerAsset to sell.
:param tx_params: transaction parameters
"""
(
orders,
taker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amount, signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
taker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amount, signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
taker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amount, signatures
).estimateGas(tx_params.as_dict())
class MarketSellOrdersNoThrowMethod(ContractMethod):
"""Various interfaces to the marketSellOrdersNoThrow method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the marketSellOrdersNoThrow method."""
self.validator.assert_valid(
method_name="marketSellOrdersNoThrow",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="marketSellOrdersNoThrow",
parameter_name="takerAssetFillAmount",
argument_value=taker_asset_fill_amount,
)
# safeguard against fractional inputs
taker_asset_fill_amount = int(taker_asset_fill_amount)
self.validator.assert_valid(
method_name="marketSellOrdersNoThrow",
parameter_name="signatures",
argument_value=signatures,
)
return (orders, taker_asset_fill_amount, signatures)
def call(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsFillResults:
"""Execute underlying contract method via eth_call.
Executes multiple calls of fillOrder until total amount of takerAsset
is sold by taker. If any fill reverts, the error is caught and ignored.
NOTE: This function does not enforce that the takerAsset is the same
for each order.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been signed by makers.
:param takerAssetFillAmount: Desired amount of takerAsset to sell.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
taker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, taker_asset_fill_amount, signatures
).call(tx_params.as_dict())
return LibFillResultsFillResults(
makerAssetFilledAmount=returned[0],
takerAssetFilledAmount=returned[1],
makerFeePaid=returned[2],
takerFeePaid=returned[3],
protocolFeePaid=returned[4],
)
def send_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes multiple calls of fillOrder until total amount of takerAsset
is sold by taker. If any fill reverts, the error is caught and ignored.
NOTE: This function does not enforce that the takerAsset is the same
for each order.
:param orders: Array of order specifications.
:param signatures: Proofs that orders have been signed by makers.
:param takerAssetFillAmount: Desired amount of takerAsset to sell.
:param tx_params: transaction parameters
"""
(
orders,
taker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amount, signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
taker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amount, signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
taker_asset_fill_amount: int,
signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
taker_asset_fill_amount,
signatures,
) = self.validate_and_normalize_inputs(
orders, taker_asset_fill_amount, signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, taker_asset_fill_amount, signatures
).estimateGas(tx_params.as_dict())
class MatchOrdersMethod(ContractMethod):
"""Various interfaces to the matchOrders method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
):
"""Validate the inputs to the matchOrders method."""
self.validator.assert_valid(
method_name="matchOrders",
parameter_name="leftOrder",
argument_value=left_order,
)
self.validator.assert_valid(
method_name="matchOrders",
parameter_name="rightOrder",
argument_value=right_order,
)
self.validator.assert_valid(
method_name="matchOrders",
parameter_name="leftSignature",
argument_value=left_signature,
)
self.validator.assert_valid(
method_name="matchOrders",
parameter_name="rightSignature",
argument_value=right_signature,
)
return (left_order, right_order, left_signature, right_signature)
def call(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsMatchedFillResults:
"""Execute underlying contract method via eth_call.
Match two complementary orders that have a profitable spread. Each
order is filled at their respective price point. However, the
calculations are carried out as though the orders are both being filled
at the right order's price point. The profit made by the left order
goes to the taker (who matched the two orders).
:param leftOrder: First order to match.
:param leftSignature: Proof that order was created by the left maker.
:param rightOrder: Second order to match.
:param rightSignature: Proof that order was created by the right maker.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
left_order,
right_order,
left_signature,
right_signature,
) = self.validate_and_normalize_inputs(
left_order, right_order, left_signature, right_signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
left_order, right_order, left_signature, right_signature
).call(tx_params.as_dict())
return LibFillResultsMatchedFillResults(
left=returned[0],
right=returned[1],
profitInLeftMakerAsset=returned[2],
profitInRightMakerAsset=returned[3],
)
def send_transaction(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Match two complementary orders that have a profitable spread. Each
order is filled at their respective price point. However, the
calculations are carried out as though the orders are both being filled
at the right order's price point. The profit made by the left order
goes to the taker (who matched the two orders).
:param leftOrder: First order to match.
:param leftSignature: Proof that order was created by the left maker.
:param rightOrder: Second order to match.
:param rightSignature: Proof that order was created by the right maker.
:param tx_params: transaction parameters
"""
(
left_order,
right_order,
left_signature,
right_signature,
) = self.validate_and_normalize_inputs(
left_order, right_order, left_signature, right_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_order, right_order, left_signature, right_signature
).transact(tx_params.as_dict())
def build_transaction(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
left_order,
right_order,
left_signature,
right_signature,
) = self.validate_and_normalize_inputs(
left_order, right_order, left_signature, right_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_order, right_order, left_signature, right_signature
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
left_order,
right_order,
left_signature,
right_signature,
) = self.validate_and_normalize_inputs(
left_order, right_order, left_signature, right_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_order, right_order, left_signature, right_signature
).estimateGas(tx_params.as_dict())
class MatchOrdersWithMaximalFillMethod(ContractMethod):
"""Various interfaces to the matchOrdersWithMaximalFill method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
):
"""Validate the inputs to the matchOrdersWithMaximalFill method."""
self.validator.assert_valid(
method_name="matchOrdersWithMaximalFill",
parameter_name="leftOrder",
argument_value=left_order,
)
self.validator.assert_valid(
method_name="matchOrdersWithMaximalFill",
parameter_name="rightOrder",
argument_value=right_order,
)
self.validator.assert_valid(
method_name="matchOrdersWithMaximalFill",
parameter_name="leftSignature",
argument_value=left_signature,
)
self.validator.assert_valid(
method_name="matchOrdersWithMaximalFill",
parameter_name="rightSignature",
argument_value=right_signature,
)
return (left_order, right_order, left_signature, right_signature)
def call(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> LibFillResultsMatchedFillResults:
"""Execute underlying contract method via eth_call.
Match two complementary orders that have a profitable spread. Each
order is maximally filled at their respective price point, and the
matcher receives a profit denominated in either the left maker asset,
right maker asset, or a combination of both.
:param leftOrder: First order to match.
:param leftSignature: Proof that order was created by the left maker.
:param rightOrder: Second order to match.
:param rightSignature: Proof that order was created by the right maker.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
left_order,
right_order,
left_signature,
right_signature,
) = self.validate_and_normalize_inputs(
left_order, right_order, left_signature, right_signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
left_order, right_order, left_signature, right_signature
).call(tx_params.as_dict())
return LibFillResultsMatchedFillResults(
left=returned[0],
right=returned[1],
profitInLeftMakerAsset=returned[2],
profitInRightMakerAsset=returned[3],
)
def send_transaction(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Match two complementary orders that have a profitable spread. Each
order is maximally filled at their respective price point, and the
matcher receives a profit denominated in either the left maker asset,
right maker asset, or a combination of both.
:param leftOrder: First order to match.
:param leftSignature: Proof that order was created by the left maker.
:param rightOrder: Second order to match.
:param rightSignature: Proof that order was created by the right maker.
:param tx_params: transaction parameters
"""
(
left_order,
right_order,
left_signature,
right_signature,
) = self.validate_and_normalize_inputs(
left_order, right_order, left_signature, right_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_order, right_order, left_signature, right_signature
).transact(tx_params.as_dict())
def build_transaction(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
left_order,
right_order,
left_signature,
right_signature,
) = self.validate_and_normalize_inputs(
left_order, right_order, left_signature, right_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_order, right_order, left_signature, right_signature
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
left_order: LibOrderOrder,
right_order: LibOrderOrder,
left_signature: Union[bytes, str],
right_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
left_order,
right_order,
left_signature,
right_signature,
) = self.validate_and_normalize_inputs(
left_order, right_order, left_signature, right_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
left_order, right_order, left_signature, right_signature
).estimateGas(tx_params.as_dict())
class OrderEpochMethod(ContractMethod):
"""Various interfaces to the orderEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str, index_1: str):
"""Validate the inputs to the orderEpoch method."""
self.validator.assert_valid(
method_name="orderEpoch",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
self.validator.assert_valid(
method_name="orderEpoch",
parameter_name="index_1",
argument_value=index_1,
)
index_1 = self.validate_and_checksum_address(index_1)
return (index_0, index_1)
def call(
self, index_0: str, index_1: str, tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0, index_1).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self, index_0: str, index_1: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0, index_1).estimateGas(
tx_params.as_dict()
)
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class PreSignMethod(ContractMethod):
"""Various interfaces to the preSign method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _hash: Union[bytes, str]):
"""Validate the inputs to the preSign method."""
self.validator.assert_valid(
method_name="preSign", parameter_name="hash", argument_value=_hash,
)
return _hash
def call(
self, _hash: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Approves a hash on-chain. After presigning a hash, the preSign
signature type will become valid for that hash and signer.
:param hash: Any 32-byte hash.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_hash) = self.validate_and_normalize_inputs(_hash)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_hash).call(tx_params.as_dict())
def send_transaction(
self, _hash: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Approves a hash on-chain. After presigning a hash, the preSign
signature type will become valid for that hash and signer.
:param hash: Any 32-byte hash.
:param tx_params: transaction parameters
"""
(_hash) = self.validate_and_normalize_inputs(_hash)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_hash).transact(tx_params.as_dict())
def build_transaction(
self, _hash: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_hash) = self.validate_and_normalize_inputs(_hash)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_hash).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _hash: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_hash) = self.validate_and_normalize_inputs(_hash)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_hash).estimateGas(tx_params.as_dict())
class PreSignedMethod(ContractMethod):
"""Various interfaces to the preSigned method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, index_0: Union[bytes, str], index_1: str
):
"""Validate the inputs to the preSigned method."""
self.validator.assert_valid(
method_name="preSigned",
parameter_name="index_0",
argument_value=index_0,
)
self.validator.assert_valid(
method_name="preSigned",
parameter_name="index_1",
argument_value=index_1,
)
index_1 = self.validate_and_checksum_address(index_1)
return (index_0, index_1)
def call(
self,
index_0: Union[bytes, str],
index_1: str,
tx_params: Optional[TxParams] = None,
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0, index_1).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self,
index_0: Union[bytes, str],
index_1: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0, index_1).estimateGas(
tx_params.as_dict()
)
class ProtocolFeeCollectorMethod(ContractMethod):
"""Various interfaces to the protocolFeeCollector method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class ProtocolFeeMultiplierMethod(ContractMethod):
"""Various interfaces to the protocolFeeMultiplier method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RegisterAssetProxyMethod(ContractMethod):
"""Various interfaces to the registerAssetProxy method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_proxy: str):
"""Validate the inputs to the registerAssetProxy method."""
self.validator.assert_valid(
method_name="registerAssetProxy",
parameter_name="assetProxy",
argument_value=asset_proxy,
)
asset_proxy = self.validate_and_checksum_address(asset_proxy)
return asset_proxy
def call(
self, asset_proxy: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Registers an asset proxy to its asset proxy id. Once an asset proxy is
registered, it cannot be unregistered.
:param assetProxy: Address of new asset proxy to register.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(asset_proxy) = self.validate_and_normalize_inputs(asset_proxy)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_proxy).call(tx_params.as_dict())
def send_transaction(
self, asset_proxy: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Registers an asset proxy to its asset proxy id. Once an asset proxy is
registered, it cannot be unregistered.
:param assetProxy: Address of new asset proxy to register.
:param tx_params: transaction parameters
"""
(asset_proxy) = self.validate_and_normalize_inputs(asset_proxy)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_proxy).transact(
tx_params.as_dict()
)
def build_transaction(
self, asset_proxy: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(asset_proxy) = self.validate_and_normalize_inputs(asset_proxy)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_proxy).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, asset_proxy: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(asset_proxy) = self.validate_and_normalize_inputs(asset_proxy)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_proxy).estimateGas(
tx_params.as_dict()
)
class SetProtocolFeeCollectorAddressMethod(ContractMethod):
"""Various interfaces to the setProtocolFeeCollectorAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, updated_protocol_fee_collector: str
):
"""Validate the inputs to the setProtocolFeeCollectorAddress method."""
self.validator.assert_valid(
method_name="setProtocolFeeCollectorAddress",
parameter_name="updatedProtocolFeeCollector",
argument_value=updated_protocol_fee_collector,
)
updated_protocol_fee_collector = self.validate_and_checksum_address(
updated_protocol_fee_collector
)
return updated_protocol_fee_collector
def call(
self,
updated_protocol_fee_collector: str,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Allows the owner to update the protocolFeeCollector address.
:param updatedProtocolFeeCollector: The updated protocolFeeCollector
contract address.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(updated_protocol_fee_collector) = self.validate_and_normalize_inputs(
updated_protocol_fee_collector
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(updated_protocol_fee_collector).call(
tx_params.as_dict()
)
def send_transaction(
self,
updated_protocol_fee_collector: str,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows the owner to update the protocolFeeCollector address.
:param updatedProtocolFeeCollector: The updated protocolFeeCollector
contract address.
:param tx_params: transaction parameters
"""
(updated_protocol_fee_collector) = self.validate_and_normalize_inputs(
updated_protocol_fee_collector
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
updated_protocol_fee_collector
).transact(tx_params.as_dict())
def build_transaction(
self,
updated_protocol_fee_collector: str,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(updated_protocol_fee_collector) = self.validate_and_normalize_inputs(
updated_protocol_fee_collector
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
updated_protocol_fee_collector
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
updated_protocol_fee_collector: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(updated_protocol_fee_collector) = self.validate_and_normalize_inputs(
updated_protocol_fee_collector
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
updated_protocol_fee_collector
).estimateGas(tx_params.as_dict())
class SetProtocolFeeMultiplierMethod(ContractMethod):
"""Various interfaces to the setProtocolFeeMultiplier method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, updated_protocol_fee_multiplier: int
):
"""Validate the inputs to the setProtocolFeeMultiplier method."""
self.validator.assert_valid(
method_name="setProtocolFeeMultiplier",
parameter_name="updatedProtocolFeeMultiplier",
argument_value=updated_protocol_fee_multiplier,
)
# safeguard against fractional inputs
updated_protocol_fee_multiplier = int(updated_protocol_fee_multiplier)
return updated_protocol_fee_multiplier
def call(
self,
updated_protocol_fee_multiplier: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Allows the owner to update the protocol fee multiplier.
:param updatedProtocolFeeMultiplier: The updated protocol fee
multiplier.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(updated_protocol_fee_multiplier) = self.validate_and_normalize_inputs(
updated_protocol_fee_multiplier
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(updated_protocol_fee_multiplier).call(
tx_params.as_dict()
)
def send_transaction(
self,
updated_protocol_fee_multiplier: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows the owner to update the protocol fee multiplier.
:param updatedProtocolFeeMultiplier: The updated protocol fee
multiplier.
:param tx_params: transaction parameters
"""
(updated_protocol_fee_multiplier) = self.validate_and_normalize_inputs(
updated_protocol_fee_multiplier
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
updated_protocol_fee_multiplier
).transact(tx_params.as_dict())
def build_transaction(
self,
updated_protocol_fee_multiplier: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(updated_protocol_fee_multiplier) = self.validate_and_normalize_inputs(
updated_protocol_fee_multiplier
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
updated_protocol_fee_multiplier
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
updated_protocol_fee_multiplier: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(updated_protocol_fee_multiplier) = self.validate_and_normalize_inputs(
updated_protocol_fee_multiplier
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
updated_protocol_fee_multiplier
).estimateGas(tx_params.as_dict())
class SetSignatureValidatorApprovalMethod(ContractMethod):
"""Various interfaces to the setSignatureValidatorApproval method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, validator_address: str, approval: bool
):
"""Validate the inputs to the setSignatureValidatorApproval method."""
self.validator.assert_valid(
method_name="setSignatureValidatorApproval",
parameter_name="validatorAddress",
argument_value=validator_address,
)
validator_address = self.validate_and_checksum_address(
validator_address
)
self.validator.assert_valid(
method_name="setSignatureValidatorApproval",
parameter_name="approval",
argument_value=approval,
)
return (validator_address, approval)
def call(
self,
validator_address: str,
approval: bool,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Approves/unnapproves a Validator contract to verify signatures on
signer's behalf using the `Validator` signature type.
:param approval: Approval or disapproval of Validator contract.
:param validatorAddress: Address of Validator contract.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(validator_address, approval) = self.validate_and_normalize_inputs(
validator_address, approval
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(validator_address, approval).call(
tx_params.as_dict()
)
def send_transaction(
self,
validator_address: str,
approval: bool,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Approves/unnapproves a Validator contract to verify signatures on
signer's behalf using the `Validator` signature type.
:param approval: Approval or disapproval of Validator contract.
:param validatorAddress: Address of Validator contract.
:param tx_params: transaction parameters
"""
(validator_address, approval) = self.validate_and_normalize_inputs(
validator_address, approval
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(validator_address, approval).transact(
tx_params.as_dict()
)
def build_transaction(
self,
validator_address: str,
approval: bool,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(validator_address, approval) = self.validate_and_normalize_inputs(
validator_address, approval
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
validator_address, approval
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
validator_address: str,
approval: bool,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(validator_address, approval) = self.validate_and_normalize_inputs(
validator_address, approval
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
validator_address, approval
).estimateGas(tx_params.as_dict())
class SimulateDispatchTransferFromCallsMethod(ContractMethod):
"""Various interfaces to the simulateDispatchTransferFromCalls method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
asset_data: List[Union[bytes, str]],
from_addresses: List[str],
to_addresses: List[str],
amounts: List[int],
):
"""Validate the inputs to the simulateDispatchTransferFromCalls method."""
self.validator.assert_valid(
method_name="simulateDispatchTransferFromCalls",
parameter_name="assetData",
argument_value=asset_data,
)
self.validator.assert_valid(
method_name="simulateDispatchTransferFromCalls",
parameter_name="fromAddresses",
argument_value=from_addresses,
)
self.validator.assert_valid(
method_name="simulateDispatchTransferFromCalls",
parameter_name="toAddresses",
argument_value=to_addresses,
)
self.validator.assert_valid(
method_name="simulateDispatchTransferFromCalls",
parameter_name="amounts",
argument_value=amounts,
)
return (asset_data, from_addresses, to_addresses, amounts)
def call(
self,
asset_data: List[Union[bytes, str]],
from_addresses: List[str],
to_addresses: List[str],
amounts: List[int],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
This function may be used to simulate any amount of transfers As they
would occur through the Exchange contract. Note that this function will
always revert, even if all transfers are successful. However, it may be
used with eth_call or with a try/catch pattern in order to simulate the
results of the transfers.
:param amounts: Array containing the amounts that correspond to each
transfer.
:param assetData: Array of asset details, each encoded per the
AssetProxy contract specification.
:param fromAddresses: Array containing the `from` addresses that
correspond with each transfer.
:param toAddresses: Array containing the `to` addresses that correspond
with each transfer.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
asset_data,
from_addresses,
to_addresses,
amounts,
) = self.validate_and_normalize_inputs(
asset_data, from_addresses, to_addresses, amounts
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(
asset_data, from_addresses, to_addresses, amounts
).call(tx_params.as_dict())
def send_transaction(
self,
asset_data: List[Union[bytes, str]],
from_addresses: List[str],
to_addresses: List[str],
amounts: List[int],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
This function may be used to simulate any amount of transfers As they
would occur through the Exchange contract. Note that this function will
always revert, even if all transfers are successful. However, it may be
used with eth_call or with a try/catch pattern in order to simulate the
results of the transfers.
:param amounts: Array containing the amounts that correspond to each
transfer.
:param assetData: Array of asset details, each encoded per the
AssetProxy contract specification.
:param fromAddresses: Array containing the `from` addresses that
correspond with each transfer.
:param toAddresses: Array containing the `to` addresses that correspond
with each transfer.
:param tx_params: transaction parameters
"""
(
asset_data,
from_addresses,
to_addresses,
amounts,
) = self.validate_and_normalize_inputs(
asset_data, from_addresses, to_addresses, amounts
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, from_addresses, to_addresses, amounts
).transact(tx_params.as_dict())
def build_transaction(
self,
asset_data: List[Union[bytes, str]],
from_addresses: List[str],
to_addresses: List[str],
amounts: List[int],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
asset_data,
from_addresses,
to_addresses,
amounts,
) = self.validate_and_normalize_inputs(
asset_data, from_addresses, to_addresses, amounts
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, from_addresses, to_addresses, amounts
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
asset_data: List[Union[bytes, str]],
from_addresses: List[str],
to_addresses: List[str],
amounts: List[int],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
asset_data,
from_addresses,
to_addresses,
amounts,
) = self.validate_and_normalize_inputs(
asset_data, from_addresses, to_addresses, amounts
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, from_addresses, to_addresses, amounts
).estimateGas(tx_params.as_dict())
class TransactionsExecutedMethod(ContractMethod):
"""Various interfaces to the transactionsExecuted method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: Union[bytes, str]):
"""Validate the inputs to the transactionsExecuted method."""
self.validator.assert_valid(
method_name="transactionsExecuted",
parameter_name="index_0",
argument_value=index_0,
)
return index_0
def call(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class Exchange:
"""Wrapper class for Exchange Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
eip1271_magic_value: Eip1271MagicValueMethod
"""Constructor-initialized instance of
:class:`Eip1271MagicValueMethod`.
"""
eip712_exchange_domain_hash: Eip712ExchangeDomainHashMethod
"""Constructor-initialized instance of
:class:`Eip712ExchangeDomainHashMethod`.
"""
allowed_validators: AllowedValidatorsMethod
"""Constructor-initialized instance of
:class:`AllowedValidatorsMethod`.
"""
batch_cancel_orders: BatchCancelOrdersMethod
"""Constructor-initialized instance of
:class:`BatchCancelOrdersMethod`.
"""
batch_execute_transactions: BatchExecuteTransactionsMethod
"""Constructor-initialized instance of
:class:`BatchExecuteTransactionsMethod`.
"""
batch_fill_or_kill_orders: BatchFillOrKillOrdersMethod
"""Constructor-initialized instance of
:class:`BatchFillOrKillOrdersMethod`.
"""
batch_fill_orders: BatchFillOrdersMethod
"""Constructor-initialized instance of
:class:`BatchFillOrdersMethod`.
"""
batch_fill_orders_no_throw: BatchFillOrdersNoThrowMethod
"""Constructor-initialized instance of
:class:`BatchFillOrdersNoThrowMethod`.
"""
batch_match_orders: BatchMatchOrdersMethod
"""Constructor-initialized instance of
:class:`BatchMatchOrdersMethod`.
"""
batch_match_orders_with_maximal_fill: BatchMatchOrdersWithMaximalFillMethod
"""Constructor-initialized instance of
:class:`BatchMatchOrdersWithMaximalFillMethod`.
"""
cancel_order: CancelOrderMethod
"""Constructor-initialized instance of
:class:`CancelOrderMethod`.
"""
cancel_orders_up_to: CancelOrdersUpToMethod
"""Constructor-initialized instance of
:class:`CancelOrdersUpToMethod`.
"""
cancelled: CancelledMethod
"""Constructor-initialized instance of
:class:`CancelledMethod`.
"""
current_context_address: CurrentContextAddressMethod
"""Constructor-initialized instance of
:class:`CurrentContextAddressMethod`.
"""
execute_transaction: ExecuteTransactionMethod
"""Constructor-initialized instance of
:class:`ExecuteTransactionMethod`.
"""
fill_or_kill_order: FillOrKillOrderMethod
"""Constructor-initialized instance of
:class:`FillOrKillOrderMethod`.
"""
fill_order: FillOrderMethod
"""Constructor-initialized instance of
:class:`FillOrderMethod`.
"""
filled: FilledMethod
"""Constructor-initialized instance of
:class:`FilledMethod`.
"""
get_asset_proxy: GetAssetProxyMethod
"""Constructor-initialized instance of
:class:`GetAssetProxyMethod`.
"""
get_order_info: GetOrderInfoMethod
"""Constructor-initialized instance of
:class:`GetOrderInfoMethod`.
"""
is_valid_hash_signature: IsValidHashSignatureMethod
"""Constructor-initialized instance of
:class:`IsValidHashSignatureMethod`.
"""
is_valid_order_signature: IsValidOrderSignatureMethod
"""Constructor-initialized instance of
:class:`IsValidOrderSignatureMethod`.
"""
is_valid_transaction_signature: IsValidTransactionSignatureMethod
"""Constructor-initialized instance of
:class:`IsValidTransactionSignatureMethod`.
"""
market_buy_orders_fill_or_kill: MarketBuyOrdersFillOrKillMethod
"""Constructor-initialized instance of
:class:`MarketBuyOrdersFillOrKillMethod`.
"""
market_buy_orders_no_throw: MarketBuyOrdersNoThrowMethod
"""Constructor-initialized instance of
:class:`MarketBuyOrdersNoThrowMethod`.
"""
market_sell_orders_fill_or_kill: MarketSellOrdersFillOrKillMethod
"""Constructor-initialized instance of
:class:`MarketSellOrdersFillOrKillMethod`.
"""
market_sell_orders_no_throw: MarketSellOrdersNoThrowMethod
"""Constructor-initialized instance of
:class:`MarketSellOrdersNoThrowMethod`.
"""
match_orders: MatchOrdersMethod
"""Constructor-initialized instance of
:class:`MatchOrdersMethod`.
"""
match_orders_with_maximal_fill: MatchOrdersWithMaximalFillMethod
"""Constructor-initialized instance of
:class:`MatchOrdersWithMaximalFillMethod`.
"""
order_epoch: OrderEpochMethod
"""Constructor-initialized instance of
:class:`OrderEpochMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
pre_sign: PreSignMethod
"""Constructor-initialized instance of
:class:`PreSignMethod`.
"""
pre_signed: PreSignedMethod
"""Constructor-initialized instance of
:class:`PreSignedMethod`.
"""
protocol_fee_collector: ProtocolFeeCollectorMethod
"""Constructor-initialized instance of
:class:`ProtocolFeeCollectorMethod`.
"""
protocol_fee_multiplier: ProtocolFeeMultiplierMethod
"""Constructor-initialized instance of
:class:`ProtocolFeeMultiplierMethod`.
"""
register_asset_proxy: RegisterAssetProxyMethod
"""Constructor-initialized instance of
:class:`RegisterAssetProxyMethod`.
"""
set_protocol_fee_collector_address: SetProtocolFeeCollectorAddressMethod
"""Constructor-initialized instance of
:class:`SetProtocolFeeCollectorAddressMethod`.
"""
set_protocol_fee_multiplier: SetProtocolFeeMultiplierMethod
"""Constructor-initialized instance of
:class:`SetProtocolFeeMultiplierMethod`.
"""
set_signature_validator_approval: SetSignatureValidatorApprovalMethod
"""Constructor-initialized instance of
:class:`SetSignatureValidatorApprovalMethod`.
"""
simulate_dispatch_transfer_from_calls: SimulateDispatchTransferFromCallsMethod
"""Constructor-initialized instance of
:class:`SimulateDispatchTransferFromCallsMethod`.
"""
transactions_executed: TransactionsExecutedMethod
"""Constructor-initialized instance of
:class:`TransactionsExecutedMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ExchangeValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ExchangeValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=Exchange.abi()
).functions
self.eip1271_magic_value = Eip1271MagicValueMethod(
web3_or_provider, contract_address, functions.EIP1271_MAGIC_VALUE
)
self.eip712_exchange_domain_hash = Eip712ExchangeDomainHashMethod(
web3_or_provider,
contract_address,
functions.EIP712_EXCHANGE_DOMAIN_HASH,
)
self.allowed_validators = AllowedValidatorsMethod(
web3_or_provider,
contract_address,
functions.allowedValidators,
validator,
)
self.batch_cancel_orders = BatchCancelOrdersMethod(
web3_or_provider,
contract_address,
functions.batchCancelOrders,
validator,
)
self.batch_execute_transactions = BatchExecuteTransactionsMethod(
web3_or_provider,
contract_address,
functions.batchExecuteTransactions,
validator,
)
self.batch_fill_or_kill_orders = BatchFillOrKillOrdersMethod(
web3_or_provider,
contract_address,
functions.batchFillOrKillOrders,
validator,
)
self.batch_fill_orders = BatchFillOrdersMethod(
web3_or_provider,
contract_address,
functions.batchFillOrders,
validator,
)
self.batch_fill_orders_no_throw = BatchFillOrdersNoThrowMethod(
web3_or_provider,
contract_address,
functions.batchFillOrdersNoThrow,
validator,
)
self.batch_match_orders = BatchMatchOrdersMethod(
web3_or_provider,
contract_address,
functions.batchMatchOrders,
validator,
)
self.batch_match_orders_with_maximal_fill = BatchMatchOrdersWithMaximalFillMethod(
web3_or_provider,
contract_address,
functions.batchMatchOrdersWithMaximalFill,
validator,
)
self.cancel_order = CancelOrderMethod(
web3_or_provider,
contract_address,
functions.cancelOrder,
validator,
)
self.cancel_orders_up_to = CancelOrdersUpToMethod(
web3_or_provider,
contract_address,
functions.cancelOrdersUpTo,
validator,
)
self.cancelled = CancelledMethod(
web3_or_provider, contract_address, functions.cancelled, validator
)
self.current_context_address = CurrentContextAddressMethod(
web3_or_provider, contract_address, functions.currentContextAddress
)
self.execute_transaction = ExecuteTransactionMethod(
web3_or_provider,
contract_address,
functions.executeTransaction,
validator,
)
self.fill_or_kill_order = FillOrKillOrderMethod(
web3_or_provider,
contract_address,
functions.fillOrKillOrder,
validator,
)
self.fill_order = FillOrderMethod(
web3_or_provider, contract_address, functions.fillOrder, validator
)
self.filled = FilledMethod(
web3_or_provider, contract_address, functions.filled, validator
)
self.get_asset_proxy = GetAssetProxyMethod(
web3_or_provider,
contract_address,
functions.getAssetProxy,
validator,
)
self.get_order_info = GetOrderInfoMethod(
web3_or_provider,
contract_address,
functions.getOrderInfo,
validator,
)
self.is_valid_hash_signature = IsValidHashSignatureMethod(
web3_or_provider,
contract_address,
functions.isValidHashSignature,
validator,
)
self.is_valid_order_signature = IsValidOrderSignatureMethod(
web3_or_provider,
contract_address,
functions.isValidOrderSignature,
validator,
)
self.is_valid_transaction_signature = IsValidTransactionSignatureMethod(
web3_or_provider,
contract_address,
functions.isValidTransactionSignature,
validator,
)
self.market_buy_orders_fill_or_kill = MarketBuyOrdersFillOrKillMethod(
web3_or_provider,
contract_address,
functions.marketBuyOrdersFillOrKill,
validator,
)
self.market_buy_orders_no_throw = MarketBuyOrdersNoThrowMethod(
web3_or_provider,
contract_address,
functions.marketBuyOrdersNoThrow,
validator,
)
self.market_sell_orders_fill_or_kill = MarketSellOrdersFillOrKillMethod(
web3_or_provider,
contract_address,
functions.marketSellOrdersFillOrKill,
validator,
)
self.market_sell_orders_no_throw = MarketSellOrdersNoThrowMethod(
web3_or_provider,
contract_address,
functions.marketSellOrdersNoThrow,
validator,
)
self.match_orders = MatchOrdersMethod(
web3_or_provider,
contract_address,
functions.matchOrders,
validator,
)
self.match_orders_with_maximal_fill = MatchOrdersWithMaximalFillMethod(
web3_or_provider,
contract_address,
functions.matchOrdersWithMaximalFill,
validator,
)
self.order_epoch = OrderEpochMethod(
web3_or_provider, contract_address, functions.orderEpoch, validator
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.pre_sign = PreSignMethod(
web3_or_provider, contract_address, functions.preSign, validator
)
self.pre_signed = PreSignedMethod(
web3_or_provider, contract_address, functions.preSigned, validator
)
self.protocol_fee_collector = ProtocolFeeCollectorMethod(
web3_or_provider, contract_address, functions.protocolFeeCollector
)
self.protocol_fee_multiplier = ProtocolFeeMultiplierMethod(
web3_or_provider, contract_address, functions.protocolFeeMultiplier
)
self.register_asset_proxy = RegisterAssetProxyMethod(
web3_or_provider,
contract_address,
functions.registerAssetProxy,
validator,
)
self.set_protocol_fee_collector_address = SetProtocolFeeCollectorAddressMethod(
web3_or_provider,
contract_address,
functions.setProtocolFeeCollectorAddress,
validator,
)
self.set_protocol_fee_multiplier = SetProtocolFeeMultiplierMethod(
web3_or_provider,
contract_address,
functions.setProtocolFeeMultiplier,
validator,
)
self.set_signature_validator_approval = SetSignatureValidatorApprovalMethod(
web3_or_provider,
contract_address,
functions.setSignatureValidatorApproval,
validator,
)
self.simulate_dispatch_transfer_from_calls = SimulateDispatchTransferFromCallsMethod(
web3_or_provider,
contract_address,
functions.simulateDispatchTransferFromCalls,
validator,
)
self.transactions_executed = TransactionsExecutedMethod(
web3_or_provider,
contract_address,
functions.transactionsExecuted,
validator,
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
def get_asset_proxy_registered_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AssetProxyRegistered event.
:param tx_hash: hash of transaction emitting AssetProxyRegistered event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Exchange.abi(),
)
.events.AssetProxyRegistered()
.processReceipt(tx_receipt)
)
def get_cancel_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Cancel event.
:param tx_hash: hash of transaction emitting Cancel event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Exchange.abi(),
)
.events.Cancel()
.processReceipt(tx_receipt)
)
def get_cancel_up_to_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for CancelUpTo event.
:param tx_hash: hash of transaction emitting CancelUpTo event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Exchange.abi(),
)
.events.CancelUpTo()
.processReceipt(tx_receipt)
)
def get_fill_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Fill event.
:param tx_hash: hash of transaction emitting Fill event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Exchange.abi(),
)
.events.Fill()
.processReceipt(tx_receipt)
)
def get_protocol_fee_collector_address_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ProtocolFeeCollectorAddress event.
:param tx_hash: hash of transaction emitting
ProtocolFeeCollectorAddress event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Exchange.abi(),
)
.events.ProtocolFeeCollectorAddress()
.processReceipt(tx_receipt)
)
def get_protocol_fee_multiplier_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ProtocolFeeMultiplier event.
:param tx_hash: hash of transaction emitting ProtocolFeeMultiplier
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Exchange.abi(),
)
.events.ProtocolFeeMultiplier()
.processReceipt(tx_receipt)
)
def get_signature_validator_approval_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for SignatureValidatorApproval event.
:param tx_hash: hash of transaction emitting SignatureValidatorApproval
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Exchange.abi(),
)
.events.SignatureValidatorApproval()
.processReceipt(tx_receipt)
)
def get_transaction_execution_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for TransactionExecution event.
:param tx_hash: hash of transaction emitting TransactionExecution event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Exchange.abi(),
)
.events.TransactionExecution()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"uint256","name":"chainId","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes4","name":"id","type":"bytes4"},{"indexed":false,"internalType":"address","name":"assetProxy","type":"address"}],"name":"AssetProxyRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"makerAddress","type":"address"},{"indexed":true,"internalType":"address","name":"feeRecipientAddress","type":"address"},{"indexed":false,"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"indexed":false,"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"indexed":false,"internalType":"address","name":"senderAddress","type":"address"},{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"name":"Cancel","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"makerAddress","type":"address"},{"indexed":true,"internalType":"address","name":"orderSenderAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"orderEpoch","type":"uint256"}],"name":"CancelUpTo","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"makerAddress","type":"address"},{"indexed":true,"internalType":"address","name":"feeRecipientAddress","type":"address"},{"indexed":false,"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"indexed":false,"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"indexed":false,"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"indexed":false,"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"},{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":false,"internalType":"address","name":"takerAddress","type":"address"},{"indexed":false,"internalType":"address","name":"senderAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"name":"Fill","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldProtocolFeeCollector","type":"address"},{"indexed":false,"internalType":"address","name":"updatedProtocolFeeCollector","type":"address"}],"name":"ProtocolFeeCollectorAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldProtocolFeeMultiplier","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"updatedProtocolFeeMultiplier","type":"uint256"}],"name":"ProtocolFeeMultiplier","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"signerAddress","type":"address"},{"indexed":true,"internalType":"address","name":"validatorAddress","type":"address"},{"indexed":false,"internalType":"bool","name":"isApproved","type":"bool"}],"name":"SignatureValidatorApproval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"transactionHash","type":"bytes32"}],"name":"TransactionExecution","type":"event"},{"constant":true,"inputs":[],"name":"EIP1271_MAGIC_VALUE","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"EIP712_EXCHANGE_DOMAIN_HASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"}],"name":"allowedValidators","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"}],"name":"batchCancelOrders","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"gasPrice","type":"uint256"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct LibZeroExTransaction.ZeroExTransaction[]","name":"transactions","type":"tuple[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"batchExecuteTransactions","outputs":[{"internalType":"bytes[]","name":"","type":"bytes[]"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256[]","name":"takerAssetFillAmounts","type":"uint256[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"batchFillOrKillOrders","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults[]","name":"fillResults","type":"tuple[]"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256[]","name":"takerAssetFillAmounts","type":"uint256[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"batchFillOrders","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults[]","name":"fillResults","type":"tuple[]"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256[]","name":"takerAssetFillAmounts","type":"uint256[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"batchFillOrdersNoThrow","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults[]","name":"fillResults","type":"tuple[]"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"leftOrders","type":"tuple[]"},{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"rightOrders","type":"tuple[]"},{"internalType":"bytes[]","name":"leftSignatures","type":"bytes[]"},{"internalType":"bytes[]","name":"rightSignatures","type":"bytes[]"}],"name":"batchMatchOrders","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults[]","name":"left","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults[]","name":"right","type":"tuple[]"},{"internalType":"uint256","name":"profitInLeftMakerAsset","type":"uint256"},{"internalType":"uint256","name":"profitInRightMakerAsset","type":"uint256"}],"internalType":"struct LibFillResults.BatchMatchedFillResults","name":"batchMatchedFillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"leftOrders","type":"tuple[]"},{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"rightOrders","type":"tuple[]"},{"internalType":"bytes[]","name":"leftSignatures","type":"bytes[]"},{"internalType":"bytes[]","name":"rightSignatures","type":"bytes[]"}],"name":"batchMatchOrdersWithMaximalFill","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults[]","name":"left","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults[]","name":"right","type":"tuple[]"},{"internalType":"uint256","name":"profitInLeftMakerAsset","type":"uint256"},{"internalType":"uint256","name":"profitInRightMakerAsset","type":"uint256"}],"internalType":"struct LibFillResults.BatchMatchedFillResults","name":"batchMatchedFillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"order","type":"tuple"}],"name":"cancelOrder","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"targetOrderEpoch","type":"uint256"}],"name":"cancelOrdersUpTo","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"index_0","type":"bytes32"}],"name":"cancelled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"currentContextAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"gasPrice","type":"uint256"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct LibZeroExTransaction.ZeroExTransaction","name":"transaction","type":"tuple"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"executeTransaction","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"order","type":"tuple"},{"internalType":"uint256","name":"takerAssetFillAmount","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"fillOrKillOrder","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"fillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"order","type":"tuple"},{"internalType":"uint256","name":"takerAssetFillAmount","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"fillOrder","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"fillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"index_0","type":"bytes32"}],"name":"filled","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"}],"name":"getAssetProxy","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"order","type":"tuple"}],"name":"getOrderInfo","outputs":[{"components":[{"internalType":"uint8","name":"orderStatus","type":"uint8"},{"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"internalType":"uint256","name":"orderTakerAssetFilledAmount","type":"uint256"}],"internalType":"struct LibOrder.OrderInfo","name":"orderInfo","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"isValidHashSignature","outputs":[{"internalType":"bool","name":"isValid","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"order","type":"tuple"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"isValidOrderSignature","outputs":[{"internalType":"bool","name":"isValid","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"gasPrice","type":"uint256"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct LibZeroExTransaction.ZeroExTransaction","name":"transaction","type":"tuple"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"isValidTransactionSignature","outputs":[{"internalType":"bool","name":"isValid","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256","name":"makerAssetFillAmount","type":"uint256"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"marketBuyOrdersFillOrKill","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"fillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256","name":"makerAssetFillAmount","type":"uint256"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"marketBuyOrdersNoThrow","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"fillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256","name":"takerAssetFillAmount","type":"uint256"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"marketSellOrdersFillOrKill","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"fillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256","name":"takerAssetFillAmount","type":"uint256"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"marketSellOrdersNoThrow","outputs":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"fillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"leftOrder","type":"tuple"},{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"rightOrder","type":"tuple"},{"internalType":"bytes","name":"leftSignature","type":"bytes"},{"internalType":"bytes","name":"rightSignature","type":"bytes"}],"name":"matchOrders","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"left","type":"tuple"},{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"right","type":"tuple"},{"internalType":"uint256","name":"profitInLeftMakerAsset","type":"uint256"},{"internalType":"uint256","name":"profitInRightMakerAsset","type":"uint256"}],"internalType":"struct LibFillResults.MatchedFillResults","name":"matchedFillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"leftOrder","type":"tuple"},{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order","name":"rightOrder","type":"tuple"},{"internalType":"bytes","name":"leftSignature","type":"bytes"},{"internalType":"bytes","name":"rightSignature","type":"bytes"}],"name":"matchOrdersWithMaximalFill","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"left","type":"tuple"},{"components":[{"internalType":"uint256","name":"makerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetFilledAmount","type":"uint256"},{"internalType":"uint256","name":"makerFeePaid","type":"uint256"},{"internalType":"uint256","name":"takerFeePaid","type":"uint256"},{"internalType":"uint256","name":"protocolFeePaid","type":"uint256"}],"internalType":"struct LibFillResults.FillResults","name":"right","type":"tuple"},{"internalType":"uint256","name":"profitInLeftMakerAsset","type":"uint256"},{"internalType":"uint256","name":"profitInRightMakerAsset","type":"uint256"}],"internalType":"struct LibFillResults.MatchedFillResults","name":"matchedFillResults","type":"tuple"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"}],"name":"orderEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"}],"name":"preSign","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"index_0","type":"bytes32"},{"internalType":"address","name":"index_1","type":"address"}],"name":"preSigned","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"protocolFeeCollector","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"protocolFeeMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"assetProxy","type":"address"}],"name":"registerAssetProxy","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"updatedProtocolFeeCollector","type":"address"}],"name":"setProtocolFeeCollectorAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"updatedProtocolFeeMultiplier","type":"uint256"}],"name":"setProtocolFeeMultiplier","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"validatorAddress","type":"address"},{"internalType":"bool","name":"approval","type":"bool"}],"name":"setSignatureValidatorApproval","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes[]","name":"assetData","type":"bytes[]"},{"internalType":"address[]","name":"fromAddresses","type":"address[]"},{"internalType":"address[]","name":"toAddresses","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"simulateDispatchTransferFromCalls","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"index_0","type":"bytes32"}],"name":"transactionsExecuted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/exchange/__init__.py | __init__.py |
"""Exchange-specific exception classes."""
from enum import auto, Enum
from zero_ex.contract_wrappers.exceptions import RichRevert
# pylint: disable=missing-docstring
class AssetProxyDispatchErrorCodes(Enum): # noqa: D101 (missing docstring)
INVALID_ASSET_DATA_LENGTH = 0
UNKNOWN_ASSET_PROXY = auto()
class BatchMatchOrdersErrorCodes(Enum): # noqa: D101 (missing docstring)
ZERO_LEFT_ORDERS = 0
ZERO_RIGHT_ORDERS = auto()
INVALID_LENGTH_LEFT_SIGNATURES = auto()
INVALID_LENGTH_RIGHT_SIGNATURES = auto()
class ExchangeContextErrorCodes(Enum): # noqa: D101 (missing docstring)
INVALID_MAKER = 0
INVALID_TAKER = auto()
INVALID_SENDER = auto()
class FillErrorCodes(Enum): # noqa: D101 (missing docstring)
INVALID_TAKER_AMOUNT = 0
TAKER_OVERPAY = auto()
OVERFILL = auto()
INVALID_FILL_PRICE = auto()
class SignatureErrorCodes(Enum): # noqa: D101 (missing docstring)
BAD_ORDER_SIGNATURE = 0
BAD_TRANSACTION_SIGNATURE = auto()
INVALID_LENGTH = auto()
UNSUPPORTED = auto()
ILLEGAL = auto()
INAPPROPRIATE_SIGNATURE_TYPE = auto()
INVALID_SIGNER = auto()
class TransactionErrorCodes(Enum): # noqa: D101 (missing docstring)
ALREADY_EXECUTED = 0
EXPIRED = auto()
class IncompleteFillErrorCode(Enum): # noqa: D101 (missing docstring)
INCOMPLETE_MARKET_BUY_ORDERS = 0
INCOMPLETE_MARKET_SELL_ORDERS = auto()
INCOMPLETE_FILL_ORDER = auto()
class SignatureError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"SignatureError(uint8,bytes32,address,bytes)",
["errorCode", "hash", "signerAddress", "signature"],
return_data,
)
errorCode: SignatureErrorCodes
hash: bytes
signerAddress: str
signature: bytes
selector = "0x7e5a2318"
class SignatureValidatorNotApprovedError(
RichRevert
): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"SignatureValidatorNotApprovedError(address,address)",
["signerAddress", "validatorAddress"],
return_data,
)
signerAddress: str
validatorAddress: str
selector = "0xa15c0d06"
class EIP1271SignatureError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"EIP1271SignatureError(address,bytes,bytes,bytes)",
["verifyingContractAddress", "data", "signature", "errorData"],
return_data,
)
verifyingContractAddress: str
data: bytes
signature: bytes
errorData: bytes
selector = "0x5bd0428d"
class SignatureWalletError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"SignatureWalletError(bytes32,address,bytes,bytes)",
["hash", "walletAddress", "signature", "errorData"],
return_data,
)
hash: bytes
walletAddress: str
signature: bytes
errorData: bytes
selector = "0x1b8388f7"
class OrderStatusError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"OrderStatusError(bytes32,uint8)",
["orderHash", "orderStatus"],
return_data,
)
orderHash: bytes
orderStatus: int
selector = "0xfdb6ca8d"
class ExchangeInvalidContextError(
RichRevert
): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"ExchangeInvalidContextError(uint8,bytes32,address)",
["errorCode", "orderHash", "contextAddress"],
return_data,
)
errorCode: ExchangeContextErrorCodes
orderHash: bytes
contextAddress: str
selector = "0xe53c76c8"
class FillError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"FillError(uint8,bytes32)", ["errorCode", "orderHash"], return_data
)
errorCode: FillErrorCodes
orderHash: bytes
selector = "0xe94a7ed0"
class OrderEpochError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"OrderEpochError(address,address,uint256)",
["makerAddress", "orderSenderAddress", "currentEpoch"],
return_data,
)
makerAddress: str
orderSenderAddress: str
currentEpoch: int
selector = "0x4ad31275"
class AssetProxyExistsError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"AssetProxyExistsError(bytes4,address)",
["assetProxyId", "assetProxyAddress"],
return_data,
)
assetProxyId: bytes
assetProxyAddress: str
selector = "0x11c7b720"
class AssetProxyDispatchError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"AssetProxyDispatchError(uint8,bytes32,bytes)",
["errorCode", "orderHash", "assetData"],
return_data,
)
errorCode: AssetProxyDispatchErrorCodes
orderHash: bytes
assetData: bytes
selector = "0x488219a6"
class AssetProxyTransferError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"AssetProxyTransferError(bytes32,bytes,bytes)",
["orderHash", "assetData", "errorData"],
return_data,
)
orderHash: bytes
assetData: bytes
errorData: bytes
selector = "0x4678472b"
class NegativeSpreadError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"NegativeSpreadError(bytes32,bytes32)",
["leftOrderHash", "rightOrderHash"],
return_data,
)
leftOrderHash: bytes
rightOrderHash: bytes
selector = "0xb6555d6f"
class TransactionError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"TransactionError(uint8,bytes32)",
["errorCode", "transactionHash"],
return_data,
)
errorCode: TransactionErrorCodes
transactionHash: bytes
selector = "0xf5985184"
class TransactionExecutionError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"TransactionExecutionError(bytes32,bytes)",
["transactionHash", "errorData"],
return_data,
)
transactionHash: bytes
errorData: bytes
selector = "0x20d11f61"
class TransactionGasPriceError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"TransactionGasPriceError(bytes32,uint256,uint256)",
["transactionHash", "actualGasPrice", "requiredGasPrice"],
return_data,
)
transactionHash: bytes
actualGasPrice: int
requiredGasPrice: int
selector = "0xa26dac09"
class TransactionInvalidContextError(
RichRevert
): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"TransactionInvalidContextError(bytes32,address)",
["transactionHash", "currentContextAddress"],
return_data,
)
transactionHash: bytes
currentContextAddress: str
selector = "0xdec4aedf"
class IncompleteFillError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"IncompleteFillError(uint8,uint256,uint256)",
["errorCode", "expectedAssetAmount", "actualAssetAmount"],
return_data,
)
errorCode: IncompleteFillErrorCode
expectedAssetAmount: int
actualAssetAmount: int
selector = "0x18e4b141"
class BatchMatchOrdersError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"BatchMatchOrdersError(uint8)", ["errorCode"], return_data
)
errorCode: BatchMatchOrdersErrorCodes
selector = "0xd4092f4f"
class PayProtocolFeeError(RichRevert): # noqa: D101 (missing docstring)
def __init__(self, return_data): # noqa: D107 (missing docstring)
super().__init__(
"PayProtocolFeeError(bytes32,uint256,address,address,bytes)",
[
"orderHash",
"protocolFee",
"makerAddress",
"takerAddress",
"errorData",
],
return_data,
)
orderHash: bytes
protocolFee: int
makerAddress: str
takerAddress: str
errorData: bytes
selector = "0x87cb1e75"
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/exchange/exceptions.py | exceptions.py |
"""Generated wrapper for StakingProxy Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for StakingProxy below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
StakingProxyValidator,
)
except ImportError:
class StakingProxyValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class AddAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the addAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the addAuthorizedAddress method."""
self.validator.assert_valid(
method_name="addAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class AggregatedStatsByEpochMethod(ContractMethod):
"""Various interfaces to the aggregatedStatsByEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the aggregatedStatsByEpoch method."""
self.validator.assert_valid(
method_name="aggregatedStatsByEpoch",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> Tuple[int, int, int, int, int]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
returned[3],
returned[4],
)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class AssertValidStorageParamsMethod(ContractMethod):
"""Various interfaces to the assertValidStorageParams method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Asserts that an epoch is between 5 and 30 days long.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method().call(tx_params.as_dict())
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AttachStakingContractMethod(ContractMethod):
"""Various interfaces to the attachStakingContract method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _staking_contract: str):
"""Validate the inputs to the attachStakingContract method."""
self.validator.assert_valid(
method_name="attachStakingContract",
parameter_name="_stakingContract",
argument_value=_staking_contract,
)
_staking_contract = self.validate_and_checksum_address(
_staking_contract
)
return _staking_contract
def call(
self, _staking_contract: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Attach a staking contract; future calls will be delegated to the
staking contract. Note that this is callable only by an authorized
address.
:param _stakingContract: Address of staking contract.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_staking_contract) = self.validate_and_normalize_inputs(
_staking_contract
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_staking_contract).call(tx_params.as_dict())
def send_transaction(
self, _staking_contract: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Attach a staking contract; future calls will be delegated to the
staking contract. Note that this is callable only by an authorized
address.
:param _stakingContract: Address of staking contract.
:param tx_params: transaction parameters
"""
(_staking_contract) = self.validate_and_normalize_inputs(
_staking_contract
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_staking_contract).transact(
tx_params.as_dict()
)
def build_transaction(
self, _staking_contract: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_staking_contract) = self.validate_and_normalize_inputs(
_staking_contract
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_staking_contract).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _staking_contract: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_staking_contract) = self.validate_and_normalize_inputs(
_staking_contract
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_staking_contract).estimateGas(
tx_params.as_dict()
)
class AuthoritiesMethod(ContractMethod):
"""Various interfaces to the authorities method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the authorities method."""
self.validator.assert_valid(
method_name="authorities",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class AuthorizedMethod(ContractMethod):
"""Various interfaces to the authorized method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the authorized method."""
self.validator.assert_valid(
method_name="authorized",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class BatchExecuteMethod(ContractMethod):
"""Various interfaces to the batchExecute method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, data: List[Union[bytes, str]]):
"""Validate the inputs to the batchExecute method."""
self.validator.assert_valid(
method_name="batchExecute",
parameter_name="data",
argument_value=data,
)
return data
def call(
self,
data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> List[Union[bytes, str]]:
"""Execute underlying contract method via eth_call.
Batch executes a series of calls to the staking contract.
:param data: An array of data that encodes a sequence of functions to
call in the staking contracts.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(data) = self.validate_and_normalize_inputs(data)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(data).call(tx_params.as_dict())
return [Union[bytes, str](element) for element in returned]
def send_transaction(
self,
data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Batch executes a series of calls to the staking contract.
:param data: An array of data that encodes a sequence of functions to
call in the staking contracts.
:param tx_params: transaction parameters
"""
(data) = self.validate_and_normalize_inputs(data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(data).transact(tx_params.as_dict())
def build_transaction(
self,
data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(data) = self.validate_and_normalize_inputs(data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(data).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(data) = self.validate_and_normalize_inputs(data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(data).estimateGas(tx_params.as_dict())
class CobbDouglasAlphaDenominatorMethod(ContractMethod):
"""Various interfaces to the cobbDouglasAlphaDenominator method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class CobbDouglasAlphaNumeratorMethod(ContractMethod):
"""Various interfaces to the cobbDouglasAlphaNumerator method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class CurrentEpochMethod(ContractMethod):
"""Various interfaces to the currentEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class CurrentEpochStartTimeInSecondsMethod(ContractMethod):
"""Various interfaces to the currentEpochStartTimeInSeconds method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class DetachStakingContractMethod(ContractMethod):
"""Various interfaces to the detachStakingContract method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Detach the current staking contract. Note that this is callable only by
an authorized address.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method().call(tx_params.as_dict())
def send_transaction(
self, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Detach the current staking contract. Note that this is callable only by
an authorized address.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().transact(tx_params.as_dict())
def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict:
"""Construct calldata to be used as input to the method."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().buildTransaction(tx_params.as_dict())
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class EpochDurationInSecondsMethod(ContractMethod):
"""Various interfaces to the epochDurationInSeconds method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetAuthorizedAddressesMethod(ContractMethod):
"""Various interfaces to the getAuthorizedAddresses method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Gets all authorized addresses.
:param tx_params: transaction parameters
:returns: Array of authorized addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class LastPoolIdMethod(ContractMethod):
"""Various interfaces to the lastPoolId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class MinimumPoolStakeMethod(ContractMethod):
"""Various interfaces to the minimumPoolStake method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class PoolIdByMakerMethod(ContractMethod):
"""Various interfaces to the poolIdByMaker method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the poolIdByMaker method."""
self.validator.assert_valid(
method_name="poolIdByMaker",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class PoolStatsByEpochMethod(ContractMethod):
"""Various interfaces to the poolStatsByEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, index_0: Union[bytes, str], index_1: int
):
"""Validate the inputs to the poolStatsByEpoch method."""
self.validator.assert_valid(
method_name="poolStatsByEpoch",
parameter_name="index_0",
argument_value=index_0,
)
self.validator.assert_valid(
method_name="poolStatsByEpoch",
parameter_name="index_1",
argument_value=index_1,
)
# safeguard against fractional inputs
index_1 = int(index_1)
return (index_0, index_1)
def call(
self,
index_0: Union[bytes, str],
index_1: int,
tx_params: Optional[TxParams] = None,
) -> Tuple[int, int, int]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0, index_1).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self,
index_0: Union[bytes, str],
index_1: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0, index_1).estimateGas(
tx_params.as_dict()
)
class RemoveAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the removeAuthorizedAddress method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressAtIndexMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddressAtIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str, index: int):
"""Validate the inputs to the removeAuthorizedAddressAtIndex method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="index",
argument_value=index,
)
# safeguard against fractional inputs
index = int(index)
return (target, index)
def call(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target, index).call(tx_params.as_dict())
def send_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).transact(
tx_params.as_dict()
)
def build_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).estimateGas(
tx_params.as_dict()
)
class RewardDelegatedStakeWeightMethod(ContractMethod):
"""Various interfaces to the rewardDelegatedStakeWeight method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RewardsByPoolIdMethod(ContractMethod):
"""Various interfaces to the rewardsByPoolId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: Union[bytes, str]):
"""Validate the inputs to the rewardsByPoolId method."""
self.validator.assert_valid(
method_name="rewardsByPoolId",
parameter_name="index_0",
argument_value=index_0,
)
return index_0
def call(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class StakingContractMethod(ContractMethod):
"""Various interfaces to the stakingContract method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
class ValidExchangesMethod(ContractMethod):
"""Various interfaces to the validExchanges method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the validExchanges method."""
self.validator.assert_valid(
method_name="validExchanges",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class WethReservedForPoolRewardsMethod(ContractMethod):
"""Various interfaces to the wethReservedForPoolRewards method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class StakingProxy:
"""Wrapper class for StakingProxy Solidity contract."""
add_authorized_address: AddAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`AddAuthorizedAddressMethod`.
"""
aggregated_stats_by_epoch: AggregatedStatsByEpochMethod
"""Constructor-initialized instance of
:class:`AggregatedStatsByEpochMethod`.
"""
assert_valid_storage_params: AssertValidStorageParamsMethod
"""Constructor-initialized instance of
:class:`AssertValidStorageParamsMethod`.
"""
attach_staking_contract: AttachStakingContractMethod
"""Constructor-initialized instance of
:class:`AttachStakingContractMethod`.
"""
authorities: AuthoritiesMethod
"""Constructor-initialized instance of
:class:`AuthoritiesMethod`.
"""
authorized: AuthorizedMethod
"""Constructor-initialized instance of
:class:`AuthorizedMethod`.
"""
batch_execute: BatchExecuteMethod
"""Constructor-initialized instance of
:class:`BatchExecuteMethod`.
"""
cobb_douglas_alpha_denominator: CobbDouglasAlphaDenominatorMethod
"""Constructor-initialized instance of
:class:`CobbDouglasAlphaDenominatorMethod`.
"""
cobb_douglas_alpha_numerator: CobbDouglasAlphaNumeratorMethod
"""Constructor-initialized instance of
:class:`CobbDouglasAlphaNumeratorMethod`.
"""
current_epoch: CurrentEpochMethod
"""Constructor-initialized instance of
:class:`CurrentEpochMethod`.
"""
current_epoch_start_time_in_seconds: CurrentEpochStartTimeInSecondsMethod
"""Constructor-initialized instance of
:class:`CurrentEpochStartTimeInSecondsMethod`.
"""
detach_staking_contract: DetachStakingContractMethod
"""Constructor-initialized instance of
:class:`DetachStakingContractMethod`.
"""
epoch_duration_in_seconds: EpochDurationInSecondsMethod
"""Constructor-initialized instance of
:class:`EpochDurationInSecondsMethod`.
"""
get_authorized_addresses: GetAuthorizedAddressesMethod
"""Constructor-initialized instance of
:class:`GetAuthorizedAddressesMethod`.
"""
last_pool_id: LastPoolIdMethod
"""Constructor-initialized instance of
:class:`LastPoolIdMethod`.
"""
minimum_pool_stake: MinimumPoolStakeMethod
"""Constructor-initialized instance of
:class:`MinimumPoolStakeMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
pool_id_by_maker: PoolIdByMakerMethod
"""Constructor-initialized instance of
:class:`PoolIdByMakerMethod`.
"""
pool_stats_by_epoch: PoolStatsByEpochMethod
"""Constructor-initialized instance of
:class:`PoolStatsByEpochMethod`.
"""
remove_authorized_address: RemoveAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressMethod`.
"""
remove_authorized_address_at_index: RemoveAuthorizedAddressAtIndexMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressAtIndexMethod`.
"""
reward_delegated_stake_weight: RewardDelegatedStakeWeightMethod
"""Constructor-initialized instance of
:class:`RewardDelegatedStakeWeightMethod`.
"""
rewards_by_pool_id: RewardsByPoolIdMethod
"""Constructor-initialized instance of
:class:`RewardsByPoolIdMethod`.
"""
staking_contract: StakingContractMethod
"""Constructor-initialized instance of
:class:`StakingContractMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
valid_exchanges: ValidExchangesMethod
"""Constructor-initialized instance of
:class:`ValidExchangesMethod`.
"""
weth_reserved_for_pool_rewards: WethReservedForPoolRewardsMethod
"""Constructor-initialized instance of
:class:`WethReservedForPoolRewardsMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: StakingProxyValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = StakingProxyValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=StakingProxy.abi(),
).functions
self.add_authorized_address = AddAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.addAuthorizedAddress,
validator,
)
self.aggregated_stats_by_epoch = AggregatedStatsByEpochMethod(
web3_or_provider,
contract_address,
functions.aggregatedStatsByEpoch,
validator,
)
self.assert_valid_storage_params = AssertValidStorageParamsMethod(
web3_or_provider,
contract_address,
functions.assertValidStorageParams,
)
self.attach_staking_contract = AttachStakingContractMethod(
web3_or_provider,
contract_address,
functions.attachStakingContract,
validator,
)
self.authorities = AuthoritiesMethod(
web3_or_provider,
contract_address,
functions.authorities,
validator,
)
self.authorized = AuthorizedMethod(
web3_or_provider, contract_address, functions.authorized, validator
)
self.batch_execute = BatchExecuteMethod(
web3_or_provider,
contract_address,
functions.batchExecute,
validator,
)
self.cobb_douglas_alpha_denominator = CobbDouglasAlphaDenominatorMethod(
web3_or_provider,
contract_address,
functions.cobbDouglasAlphaDenominator,
)
self.cobb_douglas_alpha_numerator = CobbDouglasAlphaNumeratorMethod(
web3_or_provider,
contract_address,
functions.cobbDouglasAlphaNumerator,
)
self.current_epoch = CurrentEpochMethod(
web3_or_provider, contract_address, functions.currentEpoch
)
self.current_epoch_start_time_in_seconds = CurrentEpochStartTimeInSecondsMethod(
web3_or_provider,
contract_address,
functions.currentEpochStartTimeInSeconds,
)
self.detach_staking_contract = DetachStakingContractMethod(
web3_or_provider, contract_address, functions.detachStakingContract
)
self.epoch_duration_in_seconds = EpochDurationInSecondsMethod(
web3_or_provider,
contract_address,
functions.epochDurationInSeconds,
)
self.get_authorized_addresses = GetAuthorizedAddressesMethod(
web3_or_provider,
contract_address,
functions.getAuthorizedAddresses,
)
self.last_pool_id = LastPoolIdMethod(
web3_or_provider, contract_address, functions.lastPoolId
)
self.minimum_pool_stake = MinimumPoolStakeMethod(
web3_or_provider, contract_address, functions.minimumPoolStake
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.pool_id_by_maker = PoolIdByMakerMethod(
web3_or_provider,
contract_address,
functions.poolIdByMaker,
validator,
)
self.pool_stats_by_epoch = PoolStatsByEpochMethod(
web3_or_provider,
contract_address,
functions.poolStatsByEpoch,
validator,
)
self.remove_authorized_address = RemoveAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddress,
validator,
)
self.remove_authorized_address_at_index = RemoveAuthorizedAddressAtIndexMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddressAtIndex,
validator,
)
self.reward_delegated_stake_weight = RewardDelegatedStakeWeightMethod(
web3_or_provider,
contract_address,
functions.rewardDelegatedStakeWeight,
)
self.rewards_by_pool_id = RewardsByPoolIdMethod(
web3_or_provider,
contract_address,
functions.rewardsByPoolId,
validator,
)
self.staking_contract = StakingContractMethod(
web3_or_provider, contract_address, functions.stakingContract
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
self.valid_exchanges = ValidExchangesMethod(
web3_or_provider,
contract_address,
functions.validExchanges,
validator,
)
self.weth_reserved_for_pool_rewards = WethReservedForPoolRewardsMethod(
web3_or_provider,
contract_address,
functions.wethReservedForPoolRewards,
)
def get_authorized_address_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressAdded event.
:param tx_hash: hash of transaction emitting AuthorizedAddressAdded
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=StakingProxy.abi(),
)
.events.AuthorizedAddressAdded()
.processReceipt(tx_receipt)
)
def get_authorized_address_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressRemoved event.
:param tx_hash: hash of transaction emitting AuthorizedAddressRemoved
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=StakingProxy.abi(),
)
.events.AuthorizedAddressRemoved()
.processReceipt(tx_receipt)
)
def get_ownership_transferred_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for OwnershipTransferred event.
:param tx_hash: hash of transaction emitting OwnershipTransferred event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=StakingProxy.abi(),
)
.events.OwnershipTransferred()
.processReceipt(tx_receipt)
)
def get_staking_contract_attached_to_proxy_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for StakingContractAttachedToProxy event.
:param tx_hash: hash of transaction emitting
StakingContractAttachedToProxy event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=StakingProxy.abi(),
)
.events.StakingContractAttachedToProxy()
.processReceipt(tx_receipt)
)
def get_staking_contract_detached_from_proxy_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for StakingContractDetachedFromProxy event.
:param tx_hash: hash of transaction emitting
StakingContractDetachedFromProxy event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=StakingProxy.abi(),
)
.events.StakingContractDetachedFromProxy()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"address","name":"_stakingContract","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newStakingContractAddress","type":"address"}],"name":"StakingContractAttachedToProxy","type":"event"},{"anonymous":false,"inputs":[],"name":"StakingContractDetachedFromProxy","type":"event"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"addAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"aggregatedStatsByEpoch","outputs":[{"internalType":"uint256","name":"rewardsAvailable","type":"uint256"},{"internalType":"uint256","name":"numPoolsToFinalize","type":"uint256"},{"internalType":"uint256","name":"totalFeesCollected","type":"uint256"},{"internalType":"uint256","name":"totalWeightedStake","type":"uint256"},{"internalType":"uint256","name":"totalRewardsFinalized","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"assertValidStorageParams","outputs":[],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_stakingContract","type":"address"}],"name":"attachStakingContract","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"authorities","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"authorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"batchExecute","outputs":[{"internalType":"bytes[]","name":"batchReturnData","type":"bytes[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"cobbDouglasAlphaDenominator","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"cobbDouglasAlphaNumerator","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"currentEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"currentEpochStartTimeInSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"detachStakingContract","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"epochDurationInSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAuthorizedAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"lastPoolId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"minimumPoolStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"poolIdByMaker","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"index_0","type":"bytes32"},{"internalType":"uint256","name":"index_1","type":"uint256"}],"name":"poolStatsByEpoch","outputs":[{"internalType":"uint256","name":"feesCollected","type":"uint256"},{"internalType":"uint256","name":"weightedStake","type":"uint256"},{"internalType":"uint256","name":"membersStake","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"removeAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"removeAuthorizedAddressAtIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"rewardDelegatedStakeWeight","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"index_0","type":"bytes32"}],"name":"rewardsByPoolId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"stakingContract","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"validExchanges","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"wethReservedForPoolRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/staking_proxy/__init__.py | __init__.py |
"""Generated wrapper for ERC20Token Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ERC20Token below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ERC20TokenValidator,
)
except ImportError:
class ERC20TokenValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class ApproveMethod(ContractMethod):
"""Various interfaces to the approve method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _spender: str, _value: int):
"""Validate the inputs to the approve method."""
self.validator.assert_valid(
method_name="approve",
parameter_name="_spender",
argument_value=_spender,
)
_spender = self.validate_and_checksum_address(_spender)
self.validator.assert_valid(
method_name="approve",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_spender, _value)
def call(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
`msg.sender` approves `_spender` to spend `_value` tokens
:param _spender: The address of the account able to transfer the tokens
:param _value: The amount of wei to be approved for transfer
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_spender, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
`msg.sender` approves `_spender` to spend `_value` tokens
:param _spender: The address of the account able to transfer the tokens
:param _value: The amount of wei to be approved for transfer
:param tx_params: transaction parameters
"""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).estimateGas(
tx_params.as_dict()
)
class TotalSupplyMethod(ContractMethod):
"""Various interfaces to the totalSupply method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Query total supply of token
:param tx_params: transaction parameters
:returns: Total supply of token
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _from: str, _to: str, _value: int):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_from, _to, _value)
def call(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> bool:
"""Execute underlying contract method via eth_call.
send `value` token to `to` from `from` on the condition it is approved
by `from`
:param _from: The address of the sender
:param _to: The address of the recipient
:param _value: The amount of token to be transferred
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_from, _to, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
send `value` token to `to` from `from` on the condition it is approved
by `from`
:param _from: The address of the sender
:param _to: The address of the recipient
:param _value: The amount of token to be transferred
:param tx_params: transaction parameters
"""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).estimateGas(
tx_params.as_dict()
)
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
return _owner
def call(self, _owner: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Query the balance of owner
:param _owner: The address from which the balance will be retrieved
:param tx_params: transaction parameters
:returns: Balance of owner
"""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, _owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner).estimateGas(tx_params.as_dict())
class TransferMethod(ContractMethod):
"""Various interfaces to the transfer method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _to: str, _value: int):
"""Validate the inputs to the transfer method."""
self.validator.assert_valid(
method_name="transfer", parameter_name="_to", argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="transfer",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_to, _value)
def call(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
send `value` token to `to` from `msg.sender`
:param _to: The address of the recipient
:param _value: The amount of token to be transferred
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_to, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
send `value` token to `to` from `msg.sender`
:param _to: The address of the recipient
:param _value: The amount of token to be transferred
:param tx_params: transaction parameters
"""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).estimateGas(
tx_params.as_dict()
)
class AllowanceMethod(ContractMethod):
"""Various interfaces to the allowance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str, _spender: str):
"""Validate the inputs to the allowance method."""
self.validator.assert_valid(
method_name="allowance",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
self.validator.assert_valid(
method_name="allowance",
parameter_name="_spender",
argument_value=_spender,
)
_spender = self.validate_and_checksum_address(_spender)
return (_owner, _spender)
def call(
self, _owner: str, _spender: str, tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param _owner: The address of the account owning tokens
:param _spender: The address of the account able to transfer the tokens
:param tx_params: transaction parameters
:returns: Amount of remaining tokens allowed to spent
"""
(_owner, _spender) = self.validate_and_normalize_inputs(
_owner, _spender
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner, _spender).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self, _owner: str, _spender: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner, _spender) = self.validate_and_normalize_inputs(
_owner, _spender
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner, _spender).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ERC20Token:
"""Wrapper class for ERC20Token Solidity contract."""
approve: ApproveMethod
"""Constructor-initialized instance of
:class:`ApproveMethod`.
"""
total_supply: TotalSupplyMethod
"""Constructor-initialized instance of
:class:`TotalSupplyMethod`.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
transfer: TransferMethod
"""Constructor-initialized instance of
:class:`TransferMethod`.
"""
allowance: AllowanceMethod
"""Constructor-initialized instance of
:class:`AllowanceMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ERC20TokenValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ERC20TokenValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=ERC20Token.abi()
).functions
self.approve = ApproveMethod(
web3_or_provider, contract_address, functions.approve, validator
)
self.total_supply = TotalSupplyMethod(
web3_or_provider, contract_address, functions.totalSupply
)
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.transfer = TransferMethod(
web3_or_provider, contract_address, functions.transfer, validator
)
self.allowance = AllowanceMethod(
web3_or_provider, contract_address, functions.allowance, validator
)
def get_transfer_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Transfer event.
:param tx_hash: hash of transaction emitting Transfer event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC20Token.abi(),
)
.events.Transfer()
.processReceipt(tx_receipt)
)
def get_approval_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Approval event.
:param tx_hash: hash of transaction emitting Approval event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC20Token.abi(),
)
.events.Approval()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":false,"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Approval","type":"event"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/erc20_token/__init__.py | __init__.py |
"""Generated wrapper for ZRXToken Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ZRXToken below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ZRXTokenValidator,
)
except ImportError:
class ZRXTokenValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class NameMethod(ContractMethod):
"""Various interfaces to the name method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class ApproveMethod(ContractMethod):
"""Various interfaces to the approve method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _spender: str, _value: int):
"""Validate the inputs to the approve method."""
self.validator.assert_valid(
method_name="approve",
parameter_name="_spender",
argument_value=_spender,
)
_spender = self.validate_and_checksum_address(_spender)
self.validator.assert_valid(
method_name="approve",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_spender, _value)
def call(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_spender, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).estimateGas(
tx_params.as_dict()
)
class TotalSupplyMethod(ContractMethod):
"""Various interfaces to the totalSupply method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _from: str, _to: str, _value: int):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_from, _to, _value)
def call(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> bool:
"""Execute underlying contract method via eth_call.
ERC20 transferFrom, modified such that an allowance of MAX_UINT
represents an unlimited allowance.
:param _from: Address to transfer from.
:param _to: Address to transfer to.
:param _value: Amount to transfer.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_from, _to, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
ERC20 transferFrom, modified such that an allowance of MAX_UINT
represents an unlimited allowance.
:param _from: Address to transfer from.
:param _to: Address to transfer to.
:param _value: Amount to transfer.
:param tx_params: transaction parameters
"""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).estimateGas(
tx_params.as_dict()
)
class DecimalsMethod(ContractMethod):
"""Various interfaces to the decimals method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
return _owner
def call(self, _owner: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, _owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner).estimateGas(tx_params.as_dict())
class SymbolMethod(ContractMethod):
"""Various interfaces to the symbol method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferMethod(ContractMethod):
"""Various interfaces to the transfer method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _to: str, _value: int):
"""Validate the inputs to the transfer method."""
self.validator.assert_valid(
method_name="transfer", parameter_name="_to", argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="transfer",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_to, _value)
def call(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_to, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).estimateGas(
tx_params.as_dict()
)
class AllowanceMethod(ContractMethod):
"""Various interfaces to the allowance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str, _spender: str):
"""Validate the inputs to the allowance method."""
self.validator.assert_valid(
method_name="allowance",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
self.validator.assert_valid(
method_name="allowance",
parameter_name="_spender",
argument_value=_spender,
)
_spender = self.validate_and_checksum_address(_spender)
return (_owner, _spender)
def call(
self, _owner: str, _spender: str, tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(_owner, _spender) = self.validate_and_normalize_inputs(
_owner, _spender
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner, _spender).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self, _owner: str, _spender: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner, _spender) = self.validate_and_normalize_inputs(
_owner, _spender
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner, _spender).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ZRXToken:
"""Wrapper class for ZRXToken Solidity contract."""
name: NameMethod
"""Constructor-initialized instance of
:class:`NameMethod`.
"""
approve: ApproveMethod
"""Constructor-initialized instance of
:class:`ApproveMethod`.
"""
total_supply: TotalSupplyMethod
"""Constructor-initialized instance of
:class:`TotalSupplyMethod`.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
decimals: DecimalsMethod
"""Constructor-initialized instance of
:class:`DecimalsMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
symbol: SymbolMethod
"""Constructor-initialized instance of
:class:`SymbolMethod`.
"""
transfer: TransferMethod
"""Constructor-initialized instance of
:class:`TransferMethod`.
"""
allowance: AllowanceMethod
"""Constructor-initialized instance of
:class:`AllowanceMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ZRXTokenValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ZRXTokenValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=ZRXToken.abi()
).functions
self.name = NameMethod(
web3_or_provider, contract_address, functions.name
)
self.approve = ApproveMethod(
web3_or_provider, contract_address, functions.approve, validator
)
self.total_supply = TotalSupplyMethod(
web3_or_provider, contract_address, functions.totalSupply
)
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.decimals = DecimalsMethod(
web3_or_provider, contract_address, functions.decimals
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.symbol = SymbolMethod(
web3_or_provider, contract_address, functions.symbol
)
self.transfer = TransferMethod(
web3_or_provider, contract_address, functions.transfer, validator
)
self.allowance = AllowanceMethod(
web3_or_provider, contract_address, functions.allowance, validator
)
def get_transfer_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Transfer event.
:param tx_hash: hash of transaction emitting Transfer event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZRXToken.abi(),
)
.events.Transfer()
.processReceipt(tx_receipt)
)
def get_approval_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Approval event.
:param tx_hash: hash of transaction emitting Approval event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZRXToken.abi(),
)
.events.Approval()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/zrx_token/__init__.py | __init__.py |
"""Generated wrapper for ERC721Token Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ERC721Token below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ERC721TokenValidator,
)
except ImportError:
class ERC721TokenValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class ApproveMethod(ContractMethod):
"""Various interfaces to the approve method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _approved: str, _token_id: int):
"""Validate the inputs to the approve method."""
self.validator.assert_valid(
method_name="approve",
parameter_name="_approved",
argument_value=_approved,
)
_approved = self.validate_and_checksum_address(_approved)
self.validator.assert_valid(
method_name="approve",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return (_approved, _token_id)
def call(
self,
_approved: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
The zero address indicates there is no approved address. Throws unless
`msg.sender` is the current NFT owner, or an authorized operator of the
current owner.
:param _approved: The new approved NFT controller
:param _tokenId: The NFT to approve
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_approved, _token_id) = self.validate_and_normalize_inputs(
_approved, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_approved, _token_id).call(tx_params.as_dict())
def send_transaction(
self,
_approved: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
The zero address indicates there is no approved address. Throws unless
`msg.sender` is the current NFT owner, or an authorized operator of the
current owner.
:param _approved: The new approved NFT controller
:param _tokenId: The NFT to approve
:param tx_params: transaction parameters
"""
(_approved, _token_id) = self.validate_and_normalize_inputs(
_approved, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_approved, _token_id).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_approved: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_approved, _token_id) = self.validate_and_normalize_inputs(
_approved, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_approved, _token_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_approved: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_approved, _token_id) = self.validate_and_normalize_inputs(
_approved, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_approved, _token_id).estimateGas(
tx_params.as_dict()
)
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
return _owner
def call(self, _owner: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
NFTs assigned to the zero address are considered invalid, and this
function throws for queries about the zero address.
:param _owner: An address for whom to query the balance
:param tx_params: transaction parameters
:returns: The number of NFTs owned by `_owner`, possibly zero
"""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, _owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner).estimateGas(tx_params.as_dict())
class GetApprovedMethod(ContractMethod):
"""Various interfaces to the getApproved method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _token_id: int):
"""Validate the inputs to the getApproved method."""
self.validator.assert_valid(
method_name="getApproved",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return _token_id
def call(
self, _token_id: int, tx_params: Optional[TxParams] = None
) -> str:
"""Execute underlying contract method via eth_call.
Throws if `_tokenId` is not a valid NFT.
:param _tokenId: The NFT to find the approved address for
:param tx_params: transaction parameters
:returns: The approved address for this NFT, or the zero address if
there is none
"""
(_token_id) = self.validate_and_normalize_inputs(_token_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_token_id).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, _token_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_token_id) = self.validate_and_normalize_inputs(_token_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_token_id).estimateGas(
tx_params.as_dict()
)
class IsApprovedForAllMethod(ContractMethod):
"""Various interfaces to the isApprovedForAll method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str, _operator: str):
"""Validate the inputs to the isApprovedForAll method."""
self.validator.assert_valid(
method_name="isApprovedForAll",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
self.validator.assert_valid(
method_name="isApprovedForAll",
parameter_name="_operator",
argument_value=_operator,
)
_operator = self.validate_and_checksum_address(_operator)
return (_owner, _operator)
def call(
self, _owner: str, _operator: str, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param _operator: The address that acts on behalf of the owner
:param _owner: The address that owns the NFTs
:param tx_params: transaction parameters
:returns: True if `_operator` is an approved operator for `_owner`,
false otherwise
"""
(_owner, _operator) = self.validate_and_normalize_inputs(
_owner, _operator
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner, _operator).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self, _owner: str, _operator: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner, _operator) = self.validate_and_normalize_inputs(
_owner, _operator
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner, _operator).estimateGas(
tx_params.as_dict()
)
class OwnerOfMethod(ContractMethod):
"""Various interfaces to the ownerOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _token_id: int):
"""Validate the inputs to the ownerOf method."""
self.validator.assert_valid(
method_name="ownerOf",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return _token_id
def call(
self, _token_id: int, tx_params: Optional[TxParams] = None
) -> str:
"""Execute underlying contract method via eth_call.
NFTs assigned to zero address are considered invalid, and queries about
them do throw.
:param _tokenId: The identifier for an NFT
:param tx_params: transaction parameters
:returns: The address of the owner of the NFT
"""
(_token_id) = self.validate_and_normalize_inputs(_token_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_token_id).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, _token_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_token_id) = self.validate_and_normalize_inputs(_token_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_token_id).estimateGas(
tx_params.as_dict()
)
class SafeTransferFrom1Method(ContractMethod):
"""Various interfaces to the safeTransferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _from: str, _to: str, _token_id: int
):
"""Validate the inputs to the safeTransferFrom method."""
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return (_from, _to, _token_id)
def call(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
This works identically to the other function with an extra data
parameter, except this function just sets data to "".
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, _to, _token_id).call(
tx_params.as_dict()
)
def send_transaction(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
This works identically to the other function with an extra data
parameter, except this function just sets data to "".
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
"""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).estimateGas(
tx_params.as_dict()
)
class SafeTransferFrom2Method(ContractMethod):
"""Various interfaces to the safeTransferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _from: str, _to: str, _token_id: int, _data: Union[bytes, str]
):
"""Validate the inputs to the safeTransferFrom method."""
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="_data",
argument_value=_data,
)
return (_from, _to, _token_id, _data)
def call(
self,
_from: str,
_to: str,
_token_id: int,
_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Throws unless `msg.sender` is the current owner, an authorized
operator, or the approved address for this NFT. Throws if `_from` is
not the current owner. Throws if `_to` is the zero address. Throws if
`_tokenId` is not a valid NFT. When transfer is complete, this function
checks if `_to` is a smart contract (code size > 0). If so, it calls
`onERC721Received` on `_to` and throws if the return value is not
`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
:param _data: Additional data with no specified format, sent in call to
`_to`
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _token_id, _data) = self.validate_and_normalize_inputs(
_from, _to, _token_id, _data
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, _to, _token_id, _data).call(
tx_params.as_dict()
)
def send_transaction(
self,
_from: str,
_to: str,
_token_id: int,
_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Throws unless `msg.sender` is the current owner, an authorized
operator, or the approved address for this NFT. Throws if `_from` is
not the current owner. Throws if `_to` is the zero address. Throws if
`_tokenId` is not a valid NFT. When transfer is complete, this function
checks if `_to` is a smart contract (code size > 0). If so, it calls
`onERC721Received` on `_to` and throws if the return value is not
`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
:param _data: Additional data with no specified format, sent in call to
`_to`
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
"""
(_from, _to, _token_id, _data) = self.validate_and_normalize_inputs(
_from, _to, _token_id, _data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id, _data).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_token_id: int,
_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _token_id, _data) = self.validate_and_normalize_inputs(
_from, _to, _token_id, _data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, _to, _token_id, _data
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
_from: str,
_to: str,
_token_id: int,
_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _token_id, _data) = self.validate_and_normalize_inputs(
_from, _to, _token_id, _data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, _to, _token_id, _data
).estimateGas(tx_params.as_dict())
class SetApprovalForAllMethod(ContractMethod):
"""Various interfaces to the setApprovalForAll method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _operator: str, _approved: bool):
"""Validate the inputs to the setApprovalForAll method."""
self.validator.assert_valid(
method_name="setApprovalForAll",
parameter_name="_operator",
argument_value=_operator,
)
_operator = self.validate_and_checksum_address(_operator)
self.validator.assert_valid(
method_name="setApprovalForAll",
parameter_name="_approved",
argument_value=_approved,
)
return (_operator, _approved)
def call(
self,
_operator: str,
_approved: bool,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Emits the ApprovalForAll event. The contract MUST allow multiple
operators per owner.
:param _approved: True if the operator is approved, false to revoke
approval
:param _operator: Address to add to the set of authorized operators
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_operator, _approved) = self.validate_and_normalize_inputs(
_operator, _approved
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_operator, _approved).call(tx_params.as_dict())
def send_transaction(
self,
_operator: str,
_approved: bool,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Emits the ApprovalForAll event. The contract MUST allow multiple
operators per owner.
:param _approved: True if the operator is approved, false to revoke
approval
:param _operator: Address to add to the set of authorized operators
:param tx_params: transaction parameters
"""
(_operator, _approved) = self.validate_and_normalize_inputs(
_operator, _approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_operator, _approved).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_operator: str,
_approved: bool,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_operator, _approved) = self.validate_and_normalize_inputs(
_operator, _approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_operator, _approved).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_operator: str,
_approved: bool,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_operator, _approved) = self.validate_and_normalize_inputs(
_operator, _approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_operator, _approved).estimateGas(
tx_params.as_dict()
)
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _from: str, _to: str, _token_id: int
):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_tokenId",
argument_value=_token_id,
)
# safeguard against fractional inputs
_token_id = int(_token_id)
return (_from, _to, _token_id)
def call(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Throws unless `msg.sender` is the current owner, an authorized
operator, or the approved address for this NFT. Throws if `_from` is
not the current owner. Throws if `_to` is the zero address. Throws if
`_tokenId` is not a valid NFT.
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, _to, _token_id).call(
tx_params.as_dict()
)
def send_transaction(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Throws unless `msg.sender` is the current owner, an authorized
operator, or the approved address for this NFT. Throws if `_from` is
not the current owner. Throws if `_to` is the zero address. Throws if
`_tokenId` is not a valid NFT.
:param _from: The current owner of the NFT
:param _to: The new owner
:param _tokenId: The NFT to transfer
:param tx_params: transaction parameters
"""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_from: str,
_to: str,
_token_id: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _token_id) = self.validate_and_normalize_inputs(
_from, _to, _token_id
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _token_id).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ERC721Token:
"""Wrapper class for ERC721Token Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
approve: ApproveMethod
"""Constructor-initialized instance of
:class:`ApproveMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
get_approved: GetApprovedMethod
"""Constructor-initialized instance of
:class:`GetApprovedMethod`.
"""
is_approved_for_all: IsApprovedForAllMethod
"""Constructor-initialized instance of
:class:`IsApprovedForAllMethod`.
"""
owner_of: OwnerOfMethod
"""Constructor-initialized instance of
:class:`OwnerOfMethod`.
"""
safe_transfer_from1: SafeTransferFrom1Method
"""Constructor-initialized instance of
:class:`SafeTransferFrom1Method`.
"""
safe_transfer_from2: SafeTransferFrom2Method
"""Constructor-initialized instance of
:class:`SafeTransferFrom2Method`.
"""
set_approval_for_all: SetApprovalForAllMethod
"""Constructor-initialized instance of
:class:`SetApprovalForAllMethod`.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ERC721TokenValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ERC721TokenValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=ERC721Token.abi(),
).functions
self.approve = ApproveMethod(
web3_or_provider, contract_address, functions.approve, validator
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.get_approved = GetApprovedMethod(
web3_or_provider,
contract_address,
functions.getApproved,
validator,
)
self.is_approved_for_all = IsApprovedForAllMethod(
web3_or_provider,
contract_address,
functions.isApprovedForAll,
validator,
)
self.owner_of = OwnerOfMethod(
web3_or_provider, contract_address, functions.ownerOf, validator
)
self.safe_transfer_from1 = SafeTransferFrom1Method(
web3_or_provider,
contract_address,
functions.safeTransferFrom,
validator,
)
self.safe_transfer_from2 = SafeTransferFrom2Method(
web3_or_provider,
contract_address,
functions.safeTransferFrom,
validator,
)
self.set_approval_for_all = SetApprovalForAllMethod(
web3_or_provider,
contract_address,
functions.setApprovalForAll,
validator,
)
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
def get_approval_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Approval event.
:param tx_hash: hash of transaction emitting Approval event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC721Token.abi(),
)
.events.Approval()
.processReceipt(tx_receipt)
)
def get_approval_for_all_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ApprovalForAll event.
:param tx_hash: hash of transaction emitting ApprovalForAll event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC721Token.abi(),
)
.events.ApprovalForAll()
.processReceipt(tx_receipt)
)
def get_transfer_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Transfer event.
:param tx_hash: hash of transaction emitting Transfer event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC721Token.abi(),
)
.events.Transfer()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_operator","type":"address"},{"indexed":false,"internalType":"bool","name":"_approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":true,"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"constant":false,"inputs":[{"internalType":"address","name":"_approved","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_operator","type":"address"},{"internalType":"bool","name":"_approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/erc721_token/__init__.py | __init__.py |
"""Generated wrapper for ERC20BridgeProxy Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ERC20BridgeProxy below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ERC20BridgeProxyValidator,
)
except ImportError:
class ERC20BridgeProxyValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class AddAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the addAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the addAuthorizedAddress method."""
self.validator.assert_valid(
method_name="addAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class AuthoritiesMethod(ContractMethod):
"""Various interfaces to the authorities method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the authorities method."""
self.validator.assert_valid(
method_name="authorities",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class AuthorizedMethod(ContractMethod):
"""Various interfaces to the authorized method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the authorized method."""
self.validator.assert_valid(
method_name="authorized",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, asset_data: Union[bytes, str], owner: str
):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="assetData",
argument_value=asset_data,
)
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="owner",
argument_value=owner,
)
owner = self.validate_and_checksum_address(owner)
return (asset_data, owner)
def call(
self,
asset_data: Union[bytes, str],
owner: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Execute underlying contract method via eth_call.
Retrieves the balance of `owner` for this asset.
:param tx_params: transaction parameters
:returns: balance The balance of the ERC20 token being transferred by
this asset proxy.
"""
(asset_data, owner) = self.validate_and_normalize_inputs(
asset_data, owner
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_data, owner).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self,
asset_data: Union[bytes, str],
owner: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data, owner) = self.validate_and_normalize_inputs(
asset_data, owner
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data, owner).estimateGas(
tx_params.as_dict()
)
class GetAuthorizedAddressesMethod(ContractMethod):
"""Various interfaces to the getAuthorizedAddresses method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Gets all authorized addresses.
:param tx_params: transaction parameters
:returns: Array of authorized addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetProxyIdMethod(ContractMethod):
"""Various interfaces to the getProxyId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Gets the proxy id associated with this asset proxy.
:param tx_params: transaction parameters
:returns: proxyId The proxy id.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the removeAuthorizedAddress method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressAtIndexMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddressAtIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str, index: int):
"""Validate the inputs to the removeAuthorizedAddressAtIndex method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="index",
argument_value=index,
)
# safeguard against fractional inputs
index = int(index)
return (target, index)
def call(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target, index).call(tx_params.as_dict())
def send_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).transact(
tx_params.as_dict()
)
def build_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).estimateGas(
tx_params.as_dict()
)
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, asset_data: Union[bytes, str], _from: str, to: str, amount: int
):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="assetData",
argument_value=asset_data,
)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom", parameter_name="to", argument_value=to,
)
to = self.validate_and_checksum_address(to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return (asset_data, _from, to, amount)
def call(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Calls a bridge contract to transfer `amount` of ERC20 from `from` to
`to`. Asserts that the balance of `to` has increased by `amount`.
:param amount: Amount of asset to transfer.
:param assetData: Abi-encoded data for this asset proxy encoded as:
abi.encodeWithSelector( bytes4 PROXY_ID,
address tokenAddress, address bridgeAddress,
bytes bridgeData )
:param from: Address to transfer asset from.
:param to: Address to transfer asset to.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_data, _from, to, amount).call(
tx_params.as_dict()
)
def send_transaction(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Calls a bridge contract to transfer `amount` of ERC20 from `from` to
`to`. Asserts that the balance of `to` has increased by `amount`.
:param amount: Amount of asset to transfer.
:param assetData: Abi-encoded data for this asset proxy encoded as:
abi.encodeWithSelector( bytes4 PROXY_ID,
address tokenAddress, address bridgeAddress,
bytes bridgeData )
:param from: Address to transfer asset from.
:param to: Address to transfer asset to.
:param tx_params: transaction parameters
"""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data, _from, to, amount).transact(
tx_params.as_dict()
)
def build_transaction(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, _from, to, amount
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, _from, to, amount
).estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ERC20BridgeProxy:
"""Wrapper class for ERC20BridgeProxy Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
add_authorized_address: AddAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`AddAuthorizedAddressMethod`.
"""
authorities: AuthoritiesMethod
"""Constructor-initialized instance of
:class:`AuthoritiesMethod`.
"""
authorized: AuthorizedMethod
"""Constructor-initialized instance of
:class:`AuthorizedMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
get_authorized_addresses: GetAuthorizedAddressesMethod
"""Constructor-initialized instance of
:class:`GetAuthorizedAddressesMethod`.
"""
get_proxy_id: GetProxyIdMethod
"""Constructor-initialized instance of
:class:`GetProxyIdMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
remove_authorized_address: RemoveAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressMethod`.
"""
remove_authorized_address_at_index: RemoveAuthorizedAddressAtIndexMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressAtIndexMethod`.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ERC20BridgeProxyValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ERC20BridgeProxyValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=ERC20BridgeProxy.abi(),
).functions
self.add_authorized_address = AddAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.addAuthorizedAddress,
validator,
)
self.authorities = AuthoritiesMethod(
web3_or_provider,
contract_address,
functions.authorities,
validator,
)
self.authorized = AuthorizedMethod(
web3_or_provider, contract_address, functions.authorized, validator
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.get_authorized_addresses = GetAuthorizedAddressesMethod(
web3_or_provider,
contract_address,
functions.getAuthorizedAddresses,
)
self.get_proxy_id = GetProxyIdMethod(
web3_or_provider, contract_address, functions.getProxyId
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.remove_authorized_address = RemoveAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddress,
validator,
)
self.remove_authorized_address_at_index = RemoveAuthorizedAddressAtIndexMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddressAtIndex,
validator,
)
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
def get_authorized_address_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressAdded event.
:param tx_hash: hash of transaction emitting AuthorizedAddressAdded
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC20BridgeProxy.abi(),
)
.events.AuthorizedAddressAdded()
.processReceipt(tx_receipt)
)
def get_authorized_address_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressRemoved event.
:param tx_hash: hash of transaction emitting AuthorizedAddressRemoved
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC20BridgeProxy.abi(),
)
.events.AuthorizedAddressRemoved()
.processReceipt(tx_receipt)
)
def get_ownership_transferred_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for OwnershipTransferred event.
:param tx_hash: hash of transaction emitting OwnershipTransferred event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC20BridgeProxy.abi(),
)
.events.OwnershipTransferred()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"addAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"authorities","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"authorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"},{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAuthorizedAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getProxyId","outputs":[{"internalType":"bytes4","name":"proxyId","type":"bytes4"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"removeAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"removeAuthorizedAddressAtIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/erc20_bridge_proxy/__init__.py | __init__.py |
"""Generated wrapper for Coordinator Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for Coordinator below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
CoordinatorValidator,
)
except ImportError:
class CoordinatorValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class LibZeroExTransactionZeroExTransaction(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
salt: int
expirationTimeSeconds: int
gasPrice: int
signerAddress: str
data: Union[bytes, str]
class LibOrderOrder(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerAddress: str
takerAddress: str
feeRecipientAddress: str
senderAddress: str
makerAssetAmount: int
takerAssetAmount: int
makerFee: int
takerFee: int
expirationTimeSeconds: int
salt: int
makerAssetData: Union[bytes, str]
takerAssetData: Union[bytes, str]
makerFeeAssetData: Union[bytes, str]
takerFeeAssetData: Union[bytes, str]
class LibCoordinatorApprovalCoordinatorApproval(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
txOrigin: str
transactionHash: Union[bytes, str]
transactionSignature: Union[bytes, str]
class Eip712CoordinatorApprovalSchemaHashMethod(ContractMethod):
"""Various interfaces to the EIP712_COORDINATOR_APPROVAL_SCHEMA_HASH method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class Eip712CoordinatorDomainHashMethod(ContractMethod):
"""Various interfaces to the EIP712_COORDINATOR_DOMAIN_HASH method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class Eip712CoordinatorDomainNameMethod(ContractMethod):
"""Various interfaces to the EIP712_COORDINATOR_DOMAIN_NAME method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class Eip712CoordinatorDomainVersionMethod(ContractMethod):
"""Various interfaces to the EIP712_COORDINATOR_DOMAIN_VERSION method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class Eip712ExchangeDomainHashMethod(ContractMethod):
"""Various interfaces to the EIP712_EXCHANGE_DOMAIN_HASH method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AssertValidCoordinatorApprovalsMethod(ContractMethod):
"""Various interfaces to the assertValidCoordinatorApprovals method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
transaction: LibZeroExTransactionZeroExTransaction,
tx_origin: str,
transaction_signature: Union[bytes, str],
approval_signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the assertValidCoordinatorApprovals method."""
self.validator.assert_valid(
method_name="assertValidCoordinatorApprovals",
parameter_name="transaction",
argument_value=transaction,
)
self.validator.assert_valid(
method_name="assertValidCoordinatorApprovals",
parameter_name="txOrigin",
argument_value=tx_origin,
)
tx_origin = self.validate_and_checksum_address(tx_origin)
self.validator.assert_valid(
method_name="assertValidCoordinatorApprovals",
parameter_name="transactionSignature",
argument_value=transaction_signature,
)
self.validator.assert_valid(
method_name="assertValidCoordinatorApprovals",
parameter_name="approvalSignatures",
argument_value=approval_signatures,
)
return (
transaction,
tx_origin,
transaction_signature,
approval_signatures,
)
def call(
self,
transaction: LibZeroExTransactionZeroExTransaction,
tx_origin: str,
transaction_signature: Union[bytes, str],
approval_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Validates that the 0x transaction has been approved by all of the
feeRecipients that correspond to each order in the transaction's
Exchange calldata.
:param approvalSignatures: Array of signatures that correspond to the
feeRecipients of each order in the transaction's Exchange
calldata.
:param transaction: 0x transaction containing salt, signerAddress, and
data.
:param transactionSignature: Proof that the transaction has been signed
by the signer.
:param txOrigin: Required signer of Ethereum transaction calling this
function.
:param tx_params: transaction parameters
"""
(
transaction,
tx_origin,
transaction_signature,
approval_signatures,
) = self.validate_and_normalize_inputs(
transaction, tx_origin, transaction_signature, approval_signatures
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(
transaction, tx_origin, transaction_signature, approval_signatures
).call(tx_params.as_dict())
def estimate_gas(
self,
transaction: LibZeroExTransactionZeroExTransaction,
tx_origin: str,
transaction_signature: Union[bytes, str],
approval_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
transaction,
tx_origin,
transaction_signature,
approval_signatures,
) = self.validate_and_normalize_inputs(
transaction, tx_origin, transaction_signature, approval_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
transaction, tx_origin, transaction_signature, approval_signatures
).estimateGas(tx_params.as_dict())
class DecodeOrdersFromFillDataMethod(ContractMethod):
"""Various interfaces to the decodeOrdersFromFillData method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, data: Union[bytes, str]):
"""Validate the inputs to the decodeOrdersFromFillData method."""
self.validator.assert_valid(
method_name="decodeOrdersFromFillData",
parameter_name="data",
argument_value=data,
)
return data
def call(
self, data: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> List[LibOrderOrder]:
"""Execute underlying contract method via eth_call.
Decodes the orders from Exchange calldata representing any fill method.
:param data: Exchange calldata representing a fill method.
:param tx_params: transaction parameters
:returns: orders The orders from the Exchange calldata.
"""
(data) = self.validate_and_normalize_inputs(data)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(data).call(tx_params.as_dict())
return [
LibOrderOrder(
makerAddress=element[0],
takerAddress=element[1],
feeRecipientAddress=element[2],
senderAddress=element[3],
makerAssetAmount=element[4],
takerAssetAmount=element[5],
makerFee=element[6],
takerFee=element[7],
expirationTimeSeconds=element[8],
salt=element[9],
makerAssetData=element[10],
takerAssetData=element[11],
makerFeeAssetData=element[12],
takerFeeAssetData=element[13],
)
for element in returned
]
def estimate_gas(
self, data: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(data) = self.validate_and_normalize_inputs(data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(data).estimateGas(tx_params.as_dict())
class ExecuteTransactionMethod(ContractMethod):
"""Various interfaces to the executeTransaction method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
transaction: LibZeroExTransactionZeroExTransaction,
tx_origin: str,
transaction_signature: Union[bytes, str],
approval_signatures: List[Union[bytes, str]],
):
"""Validate the inputs to the executeTransaction method."""
self.validator.assert_valid(
method_name="executeTransaction",
parameter_name="transaction",
argument_value=transaction,
)
self.validator.assert_valid(
method_name="executeTransaction",
parameter_name="txOrigin",
argument_value=tx_origin,
)
tx_origin = self.validate_and_checksum_address(tx_origin)
self.validator.assert_valid(
method_name="executeTransaction",
parameter_name="transactionSignature",
argument_value=transaction_signature,
)
self.validator.assert_valid(
method_name="executeTransaction",
parameter_name="approvalSignatures",
argument_value=approval_signatures,
)
return (
transaction,
tx_origin,
transaction_signature,
approval_signatures,
)
def call(
self,
transaction: LibZeroExTransactionZeroExTransaction,
tx_origin: str,
transaction_signature: Union[bytes, str],
approval_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Executes a 0x transaction that has been signed by the feeRecipients
that correspond to each order in the transaction's Exchange calldata.
:param approvalSignatures: Array of signatures that correspond to the
feeRecipients of each order in the transaction's Exchange
calldata.
:param transaction: 0x transaction containing salt, signerAddress, and
data.
:param transactionSignature: Proof that the transaction has been signed
by the signer.
:param txOrigin: Required signer of Ethereum transaction calling this
function.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
transaction,
tx_origin,
transaction_signature,
approval_signatures,
) = self.validate_and_normalize_inputs(
transaction, tx_origin, transaction_signature, approval_signatures
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(
transaction, tx_origin, transaction_signature, approval_signatures
).call(tx_params.as_dict())
def send_transaction(
self,
transaction: LibZeroExTransactionZeroExTransaction,
tx_origin: str,
transaction_signature: Union[bytes, str],
approval_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Executes a 0x transaction that has been signed by the feeRecipients
that correspond to each order in the transaction's Exchange calldata.
:param approvalSignatures: Array of signatures that correspond to the
feeRecipients of each order in the transaction's Exchange
calldata.
:param transaction: 0x transaction containing salt, signerAddress, and
data.
:param transactionSignature: Proof that the transaction has been signed
by the signer.
:param txOrigin: Required signer of Ethereum transaction calling this
function.
:param tx_params: transaction parameters
"""
(
transaction,
tx_origin,
transaction_signature,
approval_signatures,
) = self.validate_and_normalize_inputs(
transaction, tx_origin, transaction_signature, approval_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
transaction, tx_origin, transaction_signature, approval_signatures
).transact(tx_params.as_dict())
def build_transaction(
self,
transaction: LibZeroExTransactionZeroExTransaction,
tx_origin: str,
transaction_signature: Union[bytes, str],
approval_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
transaction,
tx_origin,
transaction_signature,
approval_signatures,
) = self.validate_and_normalize_inputs(
transaction, tx_origin, transaction_signature, approval_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
transaction, tx_origin, transaction_signature, approval_signatures
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
transaction: LibZeroExTransactionZeroExTransaction,
tx_origin: str,
transaction_signature: Union[bytes, str],
approval_signatures: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
transaction,
tx_origin,
transaction_signature,
approval_signatures,
) = self.validate_and_normalize_inputs(
transaction, tx_origin, transaction_signature, approval_signatures
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
transaction, tx_origin, transaction_signature, approval_signatures
).estimateGas(tx_params.as_dict())
class GetCoordinatorApprovalHashMethod(ContractMethod):
"""Various interfaces to the getCoordinatorApprovalHash method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, approval: LibCoordinatorApprovalCoordinatorApproval
):
"""Validate the inputs to the getCoordinatorApprovalHash method."""
self.validator.assert_valid(
method_name="getCoordinatorApprovalHash",
parameter_name="approval",
argument_value=approval,
)
return approval
def call(
self,
approval: LibCoordinatorApprovalCoordinatorApproval,
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Calculates the EIP712 hash of the Coordinator approval mesasage using
the domain separator of this contract.
:param approval: Coordinator approval message containing the
transaction hash, and transaction signature.
:param tx_params: transaction parameters
:returns: approvalHash EIP712 hash of the Coordinator approval message
with the domain separator of this contract.
"""
(approval) = self.validate_and_normalize_inputs(approval)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(approval).call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(
self,
approval: LibCoordinatorApprovalCoordinatorApproval,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(approval) = self.validate_and_normalize_inputs(approval)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(approval).estimateGas(
tx_params.as_dict()
)
class GetSignerAddressMethod(ContractMethod):
"""Various interfaces to the getSignerAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _hash: Union[bytes, str], signature: Union[bytes, str]
):
"""Validate the inputs to the getSignerAddress method."""
self.validator.assert_valid(
method_name="getSignerAddress",
parameter_name="hash",
argument_value=_hash,
)
self.validator.assert_valid(
method_name="getSignerAddress",
parameter_name="signature",
argument_value=signature,
)
return (_hash, signature)
def call(
self,
_hash: Union[bytes, str],
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> str:
"""Execute underlying contract method via eth_call.
Recovers the address of a signer given a hash and signature.
:param hash: Any 32 byte hash.
:param signature: Proof that the hash has been signed by signer.
:param tx_params: transaction parameters
:returns: signerAddress Address of the signer.
"""
(_hash, signature) = self.validate_and_normalize_inputs(
_hash, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_hash, signature).call(
tx_params.as_dict()
)
return str(returned)
def estimate_gas(
self,
_hash: Union[bytes, str],
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_hash, signature) = self.validate_and_normalize_inputs(
_hash, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_hash, signature).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class Coordinator:
"""Wrapper class for Coordinator Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
eip712_coordinator_approval_schema_hash: Eip712CoordinatorApprovalSchemaHashMethod
"""Constructor-initialized instance of
:class:`Eip712CoordinatorApprovalSchemaHashMethod`.
"""
eip712_coordinator_domain_hash: Eip712CoordinatorDomainHashMethod
"""Constructor-initialized instance of
:class:`Eip712CoordinatorDomainHashMethod`.
"""
eip712_coordinator_domain_name: Eip712CoordinatorDomainNameMethod
"""Constructor-initialized instance of
:class:`Eip712CoordinatorDomainNameMethod`.
"""
eip712_coordinator_domain_version: Eip712CoordinatorDomainVersionMethod
"""Constructor-initialized instance of
:class:`Eip712CoordinatorDomainVersionMethod`.
"""
eip712_exchange_domain_hash: Eip712ExchangeDomainHashMethod
"""Constructor-initialized instance of
:class:`Eip712ExchangeDomainHashMethod`.
"""
assert_valid_coordinator_approvals: AssertValidCoordinatorApprovalsMethod
"""Constructor-initialized instance of
:class:`AssertValidCoordinatorApprovalsMethod`.
"""
decode_orders_from_fill_data: DecodeOrdersFromFillDataMethod
"""Constructor-initialized instance of
:class:`DecodeOrdersFromFillDataMethod`.
"""
execute_transaction: ExecuteTransactionMethod
"""Constructor-initialized instance of
:class:`ExecuteTransactionMethod`.
"""
get_coordinator_approval_hash: GetCoordinatorApprovalHashMethod
"""Constructor-initialized instance of
:class:`GetCoordinatorApprovalHashMethod`.
"""
get_signer_address: GetSignerAddressMethod
"""Constructor-initialized instance of
:class:`GetSignerAddressMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: CoordinatorValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = CoordinatorValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=Coordinator.abi(),
).functions
self.eip712_coordinator_approval_schema_hash = Eip712CoordinatorApprovalSchemaHashMethod(
web3_or_provider,
contract_address,
functions.EIP712_COORDINATOR_APPROVAL_SCHEMA_HASH,
)
self.eip712_coordinator_domain_hash = Eip712CoordinatorDomainHashMethod(
web3_or_provider,
contract_address,
functions.EIP712_COORDINATOR_DOMAIN_HASH,
)
self.eip712_coordinator_domain_name = Eip712CoordinatorDomainNameMethod(
web3_or_provider,
contract_address,
functions.EIP712_COORDINATOR_DOMAIN_NAME,
)
self.eip712_coordinator_domain_version = Eip712CoordinatorDomainVersionMethod(
web3_or_provider,
contract_address,
functions.EIP712_COORDINATOR_DOMAIN_VERSION,
)
self.eip712_exchange_domain_hash = Eip712ExchangeDomainHashMethod(
web3_or_provider,
contract_address,
functions.EIP712_EXCHANGE_DOMAIN_HASH,
)
self.assert_valid_coordinator_approvals = AssertValidCoordinatorApprovalsMethod(
web3_or_provider,
contract_address,
functions.assertValidCoordinatorApprovals,
validator,
)
self.decode_orders_from_fill_data = DecodeOrdersFromFillDataMethod(
web3_or_provider,
contract_address,
functions.decodeOrdersFromFillData,
validator,
)
self.execute_transaction = ExecuteTransactionMethod(
web3_or_provider,
contract_address,
functions.executeTransaction,
validator,
)
self.get_coordinator_approval_hash = GetCoordinatorApprovalHashMethod(
web3_or_provider,
contract_address,
functions.getCoordinatorApprovalHash,
validator,
)
self.get_signer_address = GetSignerAddressMethod(
web3_or_provider,
contract_address,
functions.getSignerAddress,
validator,
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"address","name":"exchange","type":"address"},{"internalType":"uint256","name":"chainId","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":true,"inputs":[],"name":"EIP712_COORDINATOR_APPROVAL_SCHEMA_HASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"EIP712_COORDINATOR_DOMAIN_HASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"EIP712_COORDINATOR_DOMAIN_NAME","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"EIP712_COORDINATOR_DOMAIN_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"EIP712_EXCHANGE_DOMAIN_HASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"gasPrice","type":"uint256"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct LibZeroExTransaction.ZeroExTransaction","name":"transaction","type":"tuple"},{"internalType":"address","name":"txOrigin","type":"address"},{"internalType":"bytes","name":"transactionSignature","type":"bytes"},{"internalType":"bytes[]","name":"approvalSignatures","type":"bytes[]"}],"name":"assertValidCoordinatorApprovals","outputs":[],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"decodeOrdersFromFillData","outputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"gasPrice","type":"uint256"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct LibZeroExTransaction.ZeroExTransaction","name":"transaction","type":"tuple"},{"internalType":"address","name":"txOrigin","type":"address"},{"internalType":"bytes","name":"transactionSignature","type":"bytes"},{"internalType":"bytes[]","name":"approvalSignatures","type":"bytes[]"}],"name":"executeTransaction","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"components":[{"internalType":"address","name":"txOrigin","type":"address"},{"internalType":"bytes32","name":"transactionHash","type":"bytes32"},{"internalType":"bytes","name":"transactionSignature","type":"bytes"}],"internalType":"struct LibCoordinatorApproval.CoordinatorApproval","name":"approval","type":"tuple"}],"name":"getCoordinatorApprovalHash","outputs":[{"internalType":"bytes32","name":"approvalHash","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"getSignerAddress","outputs":[{"internalType":"address","name":"signerAddress","type":"address"}],"payable":false,"stateMutability":"pure","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/coordinator/__init__.py | __init__.py |
"""Generated wrapper for ERC1155Proxy Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ERC1155Proxy below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ERC1155ProxyValidator,
)
except ImportError:
class ERC1155ProxyValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class AddAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the addAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the addAuthorizedAddress method."""
self.validator.assert_valid(
method_name="addAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class AuthoritiesMethod(ContractMethod):
"""Various interfaces to the authorities method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the authorities method."""
self.validator.assert_valid(
method_name="authorities",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class AuthorizedMethod(ContractMethod):
"""Various interfaces to the authorized method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the authorized method."""
self.validator.assert_valid(
method_name="authorized",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class GetAuthorizedAddressesMethod(ContractMethod):
"""Various interfaces to the getAuthorizedAddresses method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Gets all authorized addresses.
:param tx_params: transaction parameters
:returns: Array of authorized addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetProxyIdMethod(ContractMethod):
"""Various interfaces to the getProxyId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Gets the proxy id associated with the proxy address.
:param tx_params: transaction parameters
:returns: Proxy id.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the removeAuthorizedAddress method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressAtIndexMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddressAtIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str, index: int):
"""Validate the inputs to the removeAuthorizedAddressAtIndex method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="index",
argument_value=index,
)
# safeguard against fractional inputs
index = int(index)
return (target, index)
def call(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target, index).call(tx_params.as_dict())
def send_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).transact(
tx_params.as_dict()
)
def build_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).estimateGas(
tx_params.as_dict()
)
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, asset_data: Union[bytes, str], _from: str, to: str, amount: int
):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="assetData",
argument_value=asset_data,
)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom", parameter_name="to", argument_value=to,
)
to = self.validate_and_checksum_address(to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return (asset_data, _from, to, amount)
def call(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Transfers batch of ERC1155 assets. Either succeeds or throws.
:param amount: Amount that will be multiplied with each element of
`assetData.values` to scale the values that will be
transferred.
:param assetData: Byte array encoded with ERC1155 token address, array
of ids, array of values, and callback data.
:param from: Address to transfer assets from.
:param to: Address to transfer assets to.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_data, _from, to, amount).call(
tx_params.as_dict()
)
def send_transaction(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Transfers batch of ERC1155 assets. Either succeeds or throws.
:param amount: Amount that will be multiplied with each element of
`assetData.values` to scale the values that will be
transferred.
:param assetData: Byte array encoded with ERC1155 token address, array
of ids, array of values, and callback data.
:param from: Address to transfer assets from.
:param to: Address to transfer assets to.
:param tx_params: transaction parameters
"""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data, _from, to, amount).transact(
tx_params.as_dict()
)
def build_transaction(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, _from, to, amount
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, _from, to, amount
).estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ERC1155Proxy:
"""Wrapper class for ERC1155Proxy Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
add_authorized_address: AddAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`AddAuthorizedAddressMethod`.
"""
authorities: AuthoritiesMethod
"""Constructor-initialized instance of
:class:`AuthoritiesMethod`.
"""
authorized: AuthorizedMethod
"""Constructor-initialized instance of
:class:`AuthorizedMethod`.
"""
get_authorized_addresses: GetAuthorizedAddressesMethod
"""Constructor-initialized instance of
:class:`GetAuthorizedAddressesMethod`.
"""
get_proxy_id: GetProxyIdMethod
"""Constructor-initialized instance of
:class:`GetProxyIdMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
remove_authorized_address: RemoveAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressMethod`.
"""
remove_authorized_address_at_index: RemoveAuthorizedAddressAtIndexMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressAtIndexMethod`.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ERC1155ProxyValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ERC1155ProxyValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=ERC1155Proxy.abi(),
).functions
self.add_authorized_address = AddAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.addAuthorizedAddress,
validator,
)
self.authorities = AuthoritiesMethod(
web3_or_provider,
contract_address,
functions.authorities,
validator,
)
self.authorized = AuthorizedMethod(
web3_or_provider, contract_address, functions.authorized, validator
)
self.get_authorized_addresses = GetAuthorizedAddressesMethod(
web3_or_provider,
contract_address,
functions.getAuthorizedAddresses,
)
self.get_proxy_id = GetProxyIdMethod(
web3_or_provider, contract_address, functions.getProxyId
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.remove_authorized_address = RemoveAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddress,
validator,
)
self.remove_authorized_address_at_index = RemoveAuthorizedAddressAtIndexMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddressAtIndex,
validator,
)
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
def get_authorized_address_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressAdded event.
:param tx_hash: hash of transaction emitting AuthorizedAddressAdded
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC1155Proxy.abi(),
)
.events.AuthorizedAddressAdded()
.processReceipt(tx_receipt)
)
def get_authorized_address_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressRemoved event.
:param tx_hash: hash of transaction emitting AuthorizedAddressRemoved
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC1155Proxy.abi(),
)
.events.AuthorizedAddressRemoved()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressRemoved","type":"event"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"addAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"authorities","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"authorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAuthorizedAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getProxyId","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"removeAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"removeAuthorizedAddressAtIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/erc1155_proxy/__init__.py | __init__.py |
"""Generated wrapper for Staking Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for Staking below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
StakingValidator,
)
except ImportError:
class StakingValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class IStructsStoredBalance(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
currentEpoch: int
currentEpochBalance: int
nextEpochBalance: int
class IStructsPool(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
operator: str
operatorShare: int
class IStructsPoolStats(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
feesCollected: int
weightedStake: int
membersStake: int
class IStructsStakeInfo(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
status: int
poolId: Union[bytes, str]
class AddAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the addAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the addAuthorizedAddress method."""
self.validator.assert_valid(
method_name="addAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class AddExchangeAddressMethod(ContractMethod):
"""Various interfaces to the addExchangeAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, addr: str):
"""Validate the inputs to the addExchangeAddress method."""
self.validator.assert_valid(
method_name="addExchangeAddress",
parameter_name="addr",
argument_value=addr,
)
addr = self.validate_and_checksum_address(addr)
return addr
def call(self, addr: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Adds a new exchange address
:param addr: Address of exchange contract to add
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(addr) = self.validate_and_normalize_inputs(addr)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(addr).call(tx_params.as_dict())
def send_transaction(
self, addr: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Adds a new exchange address
:param addr: Address of exchange contract to add
:param tx_params: transaction parameters
"""
(addr) = self.validate_and_normalize_inputs(addr)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addr).transact(tx_params.as_dict())
def build_transaction(
self, addr: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(addr) = self.validate_and_normalize_inputs(addr)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addr).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, addr: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(addr) = self.validate_and_normalize_inputs(addr)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addr).estimateGas(tx_params.as_dict())
class AggregatedStatsByEpochMethod(ContractMethod):
"""Various interfaces to the aggregatedStatsByEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the aggregatedStatsByEpoch method."""
self.validator.assert_valid(
method_name="aggregatedStatsByEpoch",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> Tuple[int, int, int, int, int]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
returned[3],
returned[4],
)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class AuthoritiesMethod(ContractMethod):
"""Various interfaces to the authorities method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the authorities method."""
self.validator.assert_valid(
method_name="authorities",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class AuthorizedMethod(ContractMethod):
"""Various interfaces to the authorized method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the authorized method."""
self.validator.assert_valid(
method_name="authorized",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class CobbDouglasAlphaDenominatorMethod(ContractMethod):
"""Various interfaces to the cobbDouglasAlphaDenominator method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class CobbDouglasAlphaNumeratorMethod(ContractMethod):
"""Various interfaces to the cobbDouglasAlphaNumerator method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class ComputeRewardBalanceOfDelegatorMethod(ContractMethod):
"""Various interfaces to the computeRewardBalanceOfDelegator method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, pool_id: Union[bytes, str], member: str
):
"""Validate the inputs to the computeRewardBalanceOfDelegator method."""
self.validator.assert_valid(
method_name="computeRewardBalanceOfDelegator",
parameter_name="poolId",
argument_value=pool_id,
)
self.validator.assert_valid(
method_name="computeRewardBalanceOfDelegator",
parameter_name="member",
argument_value=member,
)
member = self.validate_and_checksum_address(member)
return (pool_id, member)
def call(
self,
pool_id: Union[bytes, str],
member: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Execute underlying contract method via eth_call.
Computes the reward balance in ETH of a specific member of a pool.
:param member: The member of the pool.
:param poolId: Unique id of pool.
:param tx_params: transaction parameters
:returns: totalReward Balance in ETH.
"""
(pool_id, member) = self.validate_and_normalize_inputs(pool_id, member)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(pool_id, member).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self,
pool_id: Union[bytes, str],
member: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(pool_id, member) = self.validate_and_normalize_inputs(pool_id, member)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id, member).estimateGas(
tx_params.as_dict()
)
class ComputeRewardBalanceOfOperatorMethod(ContractMethod):
"""Various interfaces to the computeRewardBalanceOfOperator method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, pool_id: Union[bytes, str]):
"""Validate the inputs to the computeRewardBalanceOfOperator method."""
self.validator.assert_valid(
method_name="computeRewardBalanceOfOperator",
parameter_name="poolId",
argument_value=pool_id,
)
return pool_id
def call(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
Computes the reward balance in ETH of the operator of a pool.
:param poolId: Unique id of pool.
:param tx_params: transaction parameters
:returns: totalReward Balance in ETH.
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(pool_id).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).estimateGas(
tx_params.as_dict()
)
class CreateStakingPoolMethod(ContractMethod):
"""Various interfaces to the createStakingPool method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, operator_share: int, add_operator_as_maker: bool
):
"""Validate the inputs to the createStakingPool method."""
self.validator.assert_valid(
method_name="createStakingPool",
parameter_name="operatorShare",
argument_value=operator_share,
)
self.validator.assert_valid(
method_name="createStakingPool",
parameter_name="addOperatorAsMaker",
argument_value=add_operator_as_maker,
)
return (operator_share, add_operator_as_maker)
def call(
self,
operator_share: int,
add_operator_as_maker: bool,
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Create a new staking pool. The sender will be the operator of this
pool. Note that an operator must be payable.
:param addOperatorAsMaker: Adds operator to the created pool as a maker
for convenience iff true.
:param operatorShare: Portion of rewards owned by the operator, in ppm.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
operator_share,
add_operator_as_maker,
) = self.validate_and_normalize_inputs(
operator_share, add_operator_as_maker
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
operator_share, add_operator_as_maker
).call(tx_params.as_dict())
return Union[bytes, str](returned)
def send_transaction(
self,
operator_share: int,
add_operator_as_maker: bool,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Create a new staking pool. The sender will be the operator of this
pool. Note that an operator must be payable.
:param addOperatorAsMaker: Adds operator to the created pool as a maker
for convenience iff true.
:param operatorShare: Portion of rewards owned by the operator, in ppm.
:param tx_params: transaction parameters
"""
(
operator_share,
add_operator_as_maker,
) = self.validate_and_normalize_inputs(
operator_share, add_operator_as_maker
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
operator_share, add_operator_as_maker
).transact(tx_params.as_dict())
def build_transaction(
self,
operator_share: int,
add_operator_as_maker: bool,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
operator_share,
add_operator_as_maker,
) = self.validate_and_normalize_inputs(
operator_share, add_operator_as_maker
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
operator_share, add_operator_as_maker
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
operator_share: int,
add_operator_as_maker: bool,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
operator_share,
add_operator_as_maker,
) = self.validate_and_normalize_inputs(
operator_share, add_operator_as_maker
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
operator_share, add_operator_as_maker
).estimateGas(tx_params.as_dict())
class CurrentEpochMethod(ContractMethod):
"""Various interfaces to the currentEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class CurrentEpochStartTimeInSecondsMethod(ContractMethod):
"""Various interfaces to the currentEpochStartTimeInSeconds method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class DecreaseStakingPoolOperatorShareMethod(ContractMethod):
"""Various interfaces to the decreaseStakingPoolOperatorShare method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, pool_id: Union[bytes, str], new_operator_share: int
):
"""Validate the inputs to the decreaseStakingPoolOperatorShare method."""
self.validator.assert_valid(
method_name="decreaseStakingPoolOperatorShare",
parameter_name="poolId",
argument_value=pool_id,
)
self.validator.assert_valid(
method_name="decreaseStakingPoolOperatorShare",
parameter_name="newOperatorShare",
argument_value=new_operator_share,
)
return (pool_id, new_operator_share)
def call(
self,
pool_id: Union[bytes, str],
new_operator_share: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Decreases the operator share for the given pool (i.e. increases pool
rewards for members).
:param newOperatorShare: The newly decreased percentage of any rewards
owned by the operator.
:param poolId: Unique Id of pool.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(pool_id, new_operator_share) = self.validate_and_normalize_inputs(
pool_id, new_operator_share
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(pool_id, new_operator_share).call(
tx_params.as_dict()
)
def send_transaction(
self,
pool_id: Union[bytes, str],
new_operator_share: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Decreases the operator share for the given pool (i.e. increases pool
rewards for members).
:param newOperatorShare: The newly decreased percentage of any rewards
owned by the operator.
:param poolId: Unique Id of pool.
:param tx_params: transaction parameters
"""
(pool_id, new_operator_share) = self.validate_and_normalize_inputs(
pool_id, new_operator_share
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id, new_operator_share).transact(
tx_params.as_dict()
)
def build_transaction(
self,
pool_id: Union[bytes, str],
new_operator_share: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(pool_id, new_operator_share) = self.validate_and_normalize_inputs(
pool_id, new_operator_share
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
pool_id, new_operator_share
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
pool_id: Union[bytes, str],
new_operator_share: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(pool_id, new_operator_share) = self.validate_and_normalize_inputs(
pool_id, new_operator_share
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
pool_id, new_operator_share
).estimateGas(tx_params.as_dict())
class EndEpochMethod(ContractMethod):
"""Various interfaces to the endEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Begins a new epoch, preparing the prior one for finalization. Throws if
not enough time has passed between epochs or if the previous epoch was
not fully finalized.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def send_transaction(
self, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Begins a new epoch, preparing the prior one for finalization. Throws if
not enough time has passed between epochs or if the previous epoch was
not fully finalized.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().transact(tx_params.as_dict())
def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict:
"""Construct calldata to be used as input to the method."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().buildTransaction(tx_params.as_dict())
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class EpochDurationInSecondsMethod(ContractMethod):
"""Various interfaces to the epochDurationInSeconds method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class FinalizePoolMethod(ContractMethod):
"""Various interfaces to the finalizePool method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, pool_id: Union[bytes, str]):
"""Validate the inputs to the finalizePool method."""
self.validator.assert_valid(
method_name="finalizePool",
parameter_name="poolId",
argument_value=pool_id,
)
return pool_id
def call(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Instantly finalizes a single pool that earned rewards in the previous
epoch, crediting it rewards for members and withdrawing operator's
rewards as WETH. This can be called by internal functions that need to
finalize a pool immediately. Does nothing if the pool is already
finalized or did not earn rewards in the previous epoch.
:param poolId: The pool ID to finalize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(pool_id).call(tx_params.as_dict())
def send_transaction(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Instantly finalizes a single pool that earned rewards in the previous
epoch, crediting it rewards for members and withdrawing operator's
rewards as WETH. This can be called by internal functions that need to
finalize a pool immediately. Does nothing if the pool is already
finalized or did not earn rewards in the previous epoch.
:param poolId: The pool ID to finalize.
:param tx_params: transaction parameters
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).transact(tx_params.as_dict())
def build_transaction(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).estimateGas(
tx_params.as_dict()
)
class GetAuthorizedAddressesMethod(ContractMethod):
"""Various interfaces to the getAuthorizedAddresses method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Gets all authorized addresses.
:param tx_params: transaction parameters
:returns: Array of authorized addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetCurrentEpochEarliestEndTimeInSecondsMethod(ContractMethod):
"""Various interfaces to the getCurrentEpochEarliestEndTimeInSeconds method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Returns the earliest end time in seconds of this epoch. The next epoch
can begin once this time is reached. Epoch period =
[startTimeInSeconds..endTimeInSeconds)
:param tx_params: transaction parameters
:returns: Time in seconds.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetGlobalStakeByStatusMethod(ContractMethod):
"""Various interfaces to the getGlobalStakeByStatus method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, stake_status: int):
"""Validate the inputs to the getGlobalStakeByStatus method."""
self.validator.assert_valid(
method_name="getGlobalStakeByStatus",
parameter_name="stakeStatus",
argument_value=stake_status,
)
return stake_status
def call(
self, stake_status: int, tx_params: Optional[TxParams] = None
) -> IStructsStoredBalance:
"""Execute underlying contract method via eth_call.
Gets global stake for a given status.
:param stakeStatus: UNDELEGATED or DELEGATED
:param tx_params: transaction parameters
:returns: Global stake for given status.
"""
(stake_status) = self.validate_and_normalize_inputs(stake_status)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(stake_status).call(
tx_params.as_dict()
)
return IStructsStoredBalance(
currentEpoch=returned[0],
currentEpochBalance=returned[1],
nextEpochBalance=returned[2],
)
def estimate_gas(
self, stake_status: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(stake_status) = self.validate_and_normalize_inputs(stake_status)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(stake_status).estimateGas(
tx_params.as_dict()
)
class GetOwnerStakeByStatusMethod(ContractMethod):
"""Various interfaces to the getOwnerStakeByStatus method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, staker: str, stake_status: int):
"""Validate the inputs to the getOwnerStakeByStatus method."""
self.validator.assert_valid(
method_name="getOwnerStakeByStatus",
parameter_name="staker",
argument_value=staker,
)
staker = self.validate_and_checksum_address(staker)
self.validator.assert_valid(
method_name="getOwnerStakeByStatus",
parameter_name="stakeStatus",
argument_value=stake_status,
)
return (staker, stake_status)
def call(
self,
staker: str,
stake_status: int,
tx_params: Optional[TxParams] = None,
) -> IStructsStoredBalance:
"""Execute underlying contract method via eth_call.
Gets an owner's stake balances by status.
:param stakeStatus: UNDELEGATED or DELEGATED
:param staker: Owner of stake.
:param tx_params: transaction parameters
:returns: Owner's stake balances for given status.
"""
(staker, stake_status) = self.validate_and_normalize_inputs(
staker, stake_status
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(staker, stake_status).call(
tx_params.as_dict()
)
return IStructsStoredBalance(
currentEpoch=returned[0],
currentEpochBalance=returned[1],
nextEpochBalance=returned[2],
)
def estimate_gas(
self,
staker: str,
stake_status: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(staker, stake_status) = self.validate_and_normalize_inputs(
staker, stake_status
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker, stake_status).estimateGas(
tx_params.as_dict()
)
class GetParamsMethod(ContractMethod):
"""Various interfaces to the getParams method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(
self, tx_params: Optional[TxParams] = None
) -> Tuple[int, int, int, int, int]:
"""Execute underlying contract method via eth_call.
Retrieves all configurable parameter values.
:param tx_params: transaction parameters
:returns: _epochDurationInSeconds Minimum seconds between
epochs._rewardDelegatedStakeWeight How much delegated stake is
weighted vs operator stake, in ppm._minimumPoolStake Minimum amount
of stake required in a pool to collect
rewards._cobbDouglasAlphaNumerator Numerator for cobb douglas alpha
factor._cobbDouglasAlphaDenominator Denominator for cobb douglas
alpha factor.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
returned[3],
returned[4],
)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetStakeDelegatedToPoolByOwnerMethod(ContractMethod):
"""Various interfaces to the getStakeDelegatedToPoolByOwner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, staker: str, pool_id: Union[bytes, str]
):
"""Validate the inputs to the getStakeDelegatedToPoolByOwner method."""
self.validator.assert_valid(
method_name="getStakeDelegatedToPoolByOwner",
parameter_name="staker",
argument_value=staker,
)
staker = self.validate_and_checksum_address(staker)
self.validator.assert_valid(
method_name="getStakeDelegatedToPoolByOwner",
parameter_name="poolId",
argument_value=pool_id,
)
return (staker, pool_id)
def call(
self,
staker: str,
pool_id: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> IStructsStoredBalance:
"""Execute underlying contract method via eth_call.
Returns the stake delegated to a specific staking pool, by a given
staker.
:param poolId: Unique Id of pool.
:param staker: of stake.
:param tx_params: transaction parameters
:returns: Stake delegated to pool by staker.
"""
(staker, pool_id) = self.validate_and_normalize_inputs(staker, pool_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(staker, pool_id).call(
tx_params.as_dict()
)
return IStructsStoredBalance(
currentEpoch=returned[0],
currentEpochBalance=returned[1],
nextEpochBalance=returned[2],
)
def estimate_gas(
self,
staker: str,
pool_id: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(staker, pool_id) = self.validate_and_normalize_inputs(staker, pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker, pool_id).estimateGas(
tx_params.as_dict()
)
class GetStakingPoolMethod(ContractMethod):
"""Various interfaces to the getStakingPool method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, pool_id: Union[bytes, str]):
"""Validate the inputs to the getStakingPool method."""
self.validator.assert_valid(
method_name="getStakingPool",
parameter_name="poolId",
argument_value=pool_id,
)
return pool_id
def call(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> IStructsPool:
"""Execute underlying contract method via eth_call.
Returns a staking pool
:param poolId: Unique id of pool.
:param tx_params: transaction parameters
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(pool_id).call(tx_params.as_dict())
return IStructsPool(operator=returned[0], operatorShare=returned[1],)
def estimate_gas(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).estimateGas(
tx_params.as_dict()
)
class GetStakingPoolStatsThisEpochMethod(ContractMethod):
"""Various interfaces to the getStakingPoolStatsThisEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, pool_id: Union[bytes, str]):
"""Validate the inputs to the getStakingPoolStatsThisEpoch method."""
self.validator.assert_valid(
method_name="getStakingPoolStatsThisEpoch",
parameter_name="poolId",
argument_value=pool_id,
)
return pool_id
def call(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> IStructsPoolStats:
"""Execute underlying contract method via eth_call.
Get stats on a staking pool in this epoch.
:param poolId: Pool Id to query.
:param tx_params: transaction parameters
:returns: PoolStats struct for pool id.
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(pool_id).call(tx_params.as_dict())
return IStructsPoolStats(
feesCollected=returned[0],
weightedStake=returned[1],
membersStake=returned[2],
)
def estimate_gas(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).estimateGas(
tx_params.as_dict()
)
class GetTotalStakeMethod(ContractMethod):
"""Various interfaces to the getTotalStake method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, staker: str):
"""Validate the inputs to the getTotalStake method."""
self.validator.assert_valid(
method_name="getTotalStake",
parameter_name="staker",
argument_value=staker,
)
staker = self.validate_and_checksum_address(staker)
return staker
def call(self, staker: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Returns the total stake for a given staker.
:param staker: of stake.
:param tx_params: transaction parameters
:returns: Total ZRX staked by `staker`.
"""
(staker) = self.validate_and_normalize_inputs(staker)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(staker).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, staker: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(staker) = self.validate_and_normalize_inputs(staker)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker).estimateGas(tx_params.as_dict())
class GetTotalStakeDelegatedToPoolMethod(ContractMethod):
"""Various interfaces to the getTotalStakeDelegatedToPool method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, pool_id: Union[bytes, str]):
"""Validate the inputs to the getTotalStakeDelegatedToPool method."""
self.validator.assert_valid(
method_name="getTotalStakeDelegatedToPool",
parameter_name="poolId",
argument_value=pool_id,
)
return pool_id
def call(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> IStructsStoredBalance:
"""Execute underlying contract method via eth_call.
Returns the total stake delegated to a specific staking pool, across
all members.
:param poolId: Unique Id of pool.
:param tx_params: transaction parameters
:returns: Total stake delegated to pool.
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(pool_id).call(tx_params.as_dict())
return IStructsStoredBalance(
currentEpoch=returned[0],
currentEpochBalance=returned[1],
nextEpochBalance=returned[2],
)
def estimate_gas(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).estimateGas(
tx_params.as_dict()
)
class GetWethContractMethod(ContractMethod):
"""Various interfaces to the getWethContract method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
Returns the current weth contract address
:param tx_params: transaction parameters
:returns: wethContract The WETH contract instance.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetZrxVaultMethod(ContractMethod):
"""Various interfaces to the getZrxVault method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
Returns the current zrxVault address.
:param tx_params: transaction parameters
:returns: zrxVault The zrxVault contract.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class InitMethod(ContractMethod):
"""Various interfaces to the init method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Initialize storage owned by this contract. This function should not be
called directly. The StakingProxy contract will call it in
`attachStakingContract()`.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method().call(tx_params.as_dict())
def send_transaction(
self, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Initialize storage owned by this contract. This function should not be
called directly. The StakingProxy contract will call it in
`attachStakingContract()`.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().transact(tx_params.as_dict())
def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict:
"""Construct calldata to be used as input to the method."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().buildTransaction(tx_params.as_dict())
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class JoinStakingPoolAsMakerMethod(ContractMethod):
"""Various interfaces to the joinStakingPoolAsMaker method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, pool_id: Union[bytes, str]):
"""Validate the inputs to the joinStakingPoolAsMaker method."""
self.validator.assert_valid(
method_name="joinStakingPoolAsMaker",
parameter_name="poolId",
argument_value=pool_id,
)
return pool_id
def call(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Allows caller to join a staking pool as a maker.
:param poolId: Unique id of pool.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(pool_id).call(tx_params.as_dict())
def send_transaction(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Allows caller to join a staking pool as a maker.
:param poolId: Unique id of pool.
:param tx_params: transaction parameters
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).transact(tx_params.as_dict())
def build_transaction(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).estimateGas(
tx_params.as_dict()
)
class LastPoolIdMethod(ContractMethod):
"""Various interfaces to the lastPoolId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class MinimumPoolStakeMethod(ContractMethod):
"""Various interfaces to the minimumPoolStake method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class MoveStakeMethod(ContractMethod):
"""Various interfaces to the moveStake method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _from: IStructsStakeInfo, to: IStructsStakeInfo, amount: int
):
"""Validate the inputs to the moveStake method."""
self.validator.assert_valid(
method_name="moveStake",
parameter_name="from",
argument_value=_from,
)
self.validator.assert_valid(
method_name="moveStake", parameter_name="to", argument_value=to,
)
self.validator.assert_valid(
method_name="moveStake",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return (_from, to, amount)
def call(
self,
_from: IStructsStakeInfo,
to: IStructsStakeInfo,
amount: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Moves stake between statuses: 'undelegated' or 'delegated'. Delegated
stake can also be moved between pools. This change comes into effect
next epoch.
:param amount: of stake to move.
:param from: status to move stake out of.
:param to: status to move stake into.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, to, amount) = self.validate_and_normalize_inputs(
_from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, to, amount).call(tx_params.as_dict())
def send_transaction(
self,
_from: IStructsStakeInfo,
to: IStructsStakeInfo,
amount: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Moves stake between statuses: 'undelegated' or 'delegated'. Delegated
stake can also be moved between pools. This change comes into effect
next epoch.
:param amount: of stake to move.
:param from: status to move stake out of.
:param to: status to move stake into.
:param tx_params: transaction parameters
"""
(_from, to, amount) = self.validate_and_normalize_inputs(
_from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, to, amount).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: IStructsStakeInfo,
to: IStructsStakeInfo,
amount: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, to, amount) = self.validate_and_normalize_inputs(
_from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, to, amount).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_from: IStructsStakeInfo,
to: IStructsStakeInfo,
amount: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, to, amount) = self.validate_and_normalize_inputs(
_from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, to, amount).estimateGas(
tx_params.as_dict()
)
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class PayProtocolFeeMethod(ContractMethod):
"""Various interfaces to the payProtocolFee method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, maker_address: str, payer_address: str, protocol_fee: int
):
"""Validate the inputs to the payProtocolFee method."""
self.validator.assert_valid(
method_name="payProtocolFee",
parameter_name="makerAddress",
argument_value=maker_address,
)
maker_address = self.validate_and_checksum_address(maker_address)
self.validator.assert_valid(
method_name="payProtocolFee",
parameter_name="payerAddress",
argument_value=payer_address,
)
payer_address = self.validate_and_checksum_address(payer_address)
self.validator.assert_valid(
method_name="payProtocolFee",
parameter_name="protocolFee",
argument_value=protocol_fee,
)
# safeguard against fractional inputs
protocol_fee = int(protocol_fee)
return (maker_address, payer_address, protocol_fee)
def call(
self,
maker_address: str,
payer_address: str,
protocol_fee: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Pays a protocol fee in ETH or WETH. Only a known 0x exchange can call
this method. See (MixinExchangeManager).
:param makerAddress: The address of the order's maker.
:param payerAddress: The address of the protocol fee payer.
:param protocolFee: The protocol fee amount. This is either passed as
ETH or transferred as WETH.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
maker_address,
payer_address,
protocol_fee,
) = self.validate_and_normalize_inputs(
maker_address, payer_address, protocol_fee
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(
maker_address, payer_address, protocol_fee
).call(tx_params.as_dict())
def send_transaction(
self,
maker_address: str,
payer_address: str,
protocol_fee: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Pays a protocol fee in ETH or WETH. Only a known 0x exchange can call
this method. See (MixinExchangeManager).
:param makerAddress: The address of the order's maker.
:param payerAddress: The address of the protocol fee payer.
:param protocolFee: The protocol fee amount. This is either passed as
ETH or transferred as WETH.
:param tx_params: transaction parameters
"""
(
maker_address,
payer_address,
protocol_fee,
) = self.validate_and_normalize_inputs(
maker_address, payer_address, protocol_fee
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
maker_address, payer_address, protocol_fee
).transact(tx_params.as_dict())
def build_transaction(
self,
maker_address: str,
payer_address: str,
protocol_fee: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
maker_address,
payer_address,
protocol_fee,
) = self.validate_and_normalize_inputs(
maker_address, payer_address, protocol_fee
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
maker_address, payer_address, protocol_fee
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
maker_address: str,
payer_address: str,
protocol_fee: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
maker_address,
payer_address,
protocol_fee,
) = self.validate_and_normalize_inputs(
maker_address, payer_address, protocol_fee
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
maker_address, payer_address, protocol_fee
).estimateGas(tx_params.as_dict())
class PoolIdByMakerMethod(ContractMethod):
"""Various interfaces to the poolIdByMaker method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the poolIdByMaker method."""
self.validator.assert_valid(
method_name="poolIdByMaker",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class PoolStatsByEpochMethod(ContractMethod):
"""Various interfaces to the poolStatsByEpoch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, index_0: Union[bytes, str], index_1: int
):
"""Validate the inputs to the poolStatsByEpoch method."""
self.validator.assert_valid(
method_name="poolStatsByEpoch",
parameter_name="index_0",
argument_value=index_0,
)
self.validator.assert_valid(
method_name="poolStatsByEpoch",
parameter_name="index_1",
argument_value=index_1,
)
# safeguard against fractional inputs
index_1 = int(index_1)
return (index_0, index_1)
def call(
self,
index_0: Union[bytes, str],
index_1: int,
tx_params: Optional[TxParams] = None,
) -> Tuple[int, int, int]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0, index_1).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
returned[2],
)
def estimate_gas(
self,
index_0: Union[bytes, str],
index_1: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0, index_1).estimateGas(
tx_params.as_dict()
)
class RemoveAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the removeAuthorizedAddress method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressAtIndexMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddressAtIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str, index: int):
"""Validate the inputs to the removeAuthorizedAddressAtIndex method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="index",
argument_value=index,
)
# safeguard against fractional inputs
index = int(index)
return (target, index)
def call(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target, index).call(tx_params.as_dict())
def send_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).transact(
tx_params.as_dict()
)
def build_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).estimateGas(
tx_params.as_dict()
)
class RemoveExchangeAddressMethod(ContractMethod):
"""Various interfaces to the removeExchangeAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, addr: str):
"""Validate the inputs to the removeExchangeAddress method."""
self.validator.assert_valid(
method_name="removeExchangeAddress",
parameter_name="addr",
argument_value=addr,
)
addr = self.validate_and_checksum_address(addr)
return addr
def call(self, addr: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes an existing exchange address
:param addr: Address of exchange contract to remove
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(addr) = self.validate_and_normalize_inputs(addr)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(addr).call(tx_params.as_dict())
def send_transaction(
self, addr: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes an existing exchange address
:param addr: Address of exchange contract to remove
:param tx_params: transaction parameters
"""
(addr) = self.validate_and_normalize_inputs(addr)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addr).transact(tx_params.as_dict())
def build_transaction(
self, addr: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(addr) = self.validate_and_normalize_inputs(addr)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addr).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, addr: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(addr) = self.validate_and_normalize_inputs(addr)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addr).estimateGas(tx_params.as_dict())
class RewardDelegatedStakeWeightMethod(ContractMethod):
"""Various interfaces to the rewardDelegatedStakeWeight method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RewardsByPoolIdMethod(ContractMethod):
"""Various interfaces to the rewardsByPoolId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: Union[bytes, str]):
"""Validate the inputs to the rewardsByPoolId method."""
self.validator.assert_valid(
method_name="rewardsByPoolId",
parameter_name="index_0",
argument_value=index_0,
)
return index_0
def call(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class SetParamsMethod(ContractMethod):
"""Various interfaces to the setParams method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
_epoch_duration_in_seconds: int,
_reward_delegated_stake_weight: int,
_minimum_pool_stake: int,
_cobb_douglas_alpha_numerator: int,
_cobb_douglas_alpha_denominator: int,
):
"""Validate the inputs to the setParams method."""
self.validator.assert_valid(
method_name="setParams",
parameter_name="_epochDurationInSeconds",
argument_value=_epoch_duration_in_seconds,
)
# safeguard against fractional inputs
_epoch_duration_in_seconds = int(_epoch_duration_in_seconds)
self.validator.assert_valid(
method_name="setParams",
parameter_name="_rewardDelegatedStakeWeight",
argument_value=_reward_delegated_stake_weight,
)
self.validator.assert_valid(
method_name="setParams",
parameter_name="_minimumPoolStake",
argument_value=_minimum_pool_stake,
)
# safeguard against fractional inputs
_minimum_pool_stake = int(_minimum_pool_stake)
self.validator.assert_valid(
method_name="setParams",
parameter_name="_cobbDouglasAlphaNumerator",
argument_value=_cobb_douglas_alpha_numerator,
)
self.validator.assert_valid(
method_name="setParams",
parameter_name="_cobbDouglasAlphaDenominator",
argument_value=_cobb_douglas_alpha_denominator,
)
return (
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
)
def call(
self,
_epoch_duration_in_seconds: int,
_reward_delegated_stake_weight: int,
_minimum_pool_stake: int,
_cobb_douglas_alpha_numerator: int,
_cobb_douglas_alpha_denominator: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Set all configurable parameters at once.
:param _cobbDouglasAlphaDenominator: Denominator for cobb douglas alpha
factor.
:param _cobbDouglasAlphaNumerator: Numerator for cobb douglas alpha
factor.
:param _epochDurationInSeconds: Minimum seconds between epochs.
:param _minimumPoolStake: Minimum amount of stake required in a pool to
collect rewards.
:param _rewardDelegatedStakeWeight: How much delegated stake is
weighted vs operator stake, in ppm.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
) = self.validate_and_normalize_inputs(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
).call(tx_params.as_dict())
def send_transaction(
self,
_epoch_duration_in_seconds: int,
_reward_delegated_stake_weight: int,
_minimum_pool_stake: int,
_cobb_douglas_alpha_numerator: int,
_cobb_douglas_alpha_denominator: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Set all configurable parameters at once.
:param _cobbDouglasAlphaDenominator: Denominator for cobb douglas alpha
factor.
:param _cobbDouglasAlphaNumerator: Numerator for cobb douglas alpha
factor.
:param _epochDurationInSeconds: Minimum seconds between epochs.
:param _minimumPoolStake: Minimum amount of stake required in a pool to
collect rewards.
:param _rewardDelegatedStakeWeight: How much delegated stake is
weighted vs operator stake, in ppm.
:param tx_params: transaction parameters
"""
(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
) = self.validate_and_normalize_inputs(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
).transact(tx_params.as_dict())
def build_transaction(
self,
_epoch_duration_in_seconds: int,
_reward_delegated_stake_weight: int,
_minimum_pool_stake: int,
_cobb_douglas_alpha_numerator: int,
_cobb_douglas_alpha_denominator: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
) = self.validate_and_normalize_inputs(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
_epoch_duration_in_seconds: int,
_reward_delegated_stake_weight: int,
_minimum_pool_stake: int,
_cobb_douglas_alpha_numerator: int,
_cobb_douglas_alpha_denominator: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
) = self.validate_and_normalize_inputs(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_epoch_duration_in_seconds,
_reward_delegated_stake_weight,
_minimum_pool_stake,
_cobb_douglas_alpha_numerator,
_cobb_douglas_alpha_denominator,
).estimateGas(tx_params.as_dict())
class StakeMethod(ContractMethod):
"""Various interfaces to the stake method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, amount: int):
"""Validate the inputs to the stake method."""
self.validator.assert_valid(
method_name="stake",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return amount
def call(self, amount: int, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Stake ZRX tokens. Tokens are deposited into the ZRX Vault. Unstake to
retrieve the ZRX. Stake is in the 'Active' status.
:param amount: of ZRX to stake.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(amount) = self.validate_and_normalize_inputs(amount)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(amount).call(tx_params.as_dict())
def send_transaction(
self, amount: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Stake ZRX tokens. Tokens are deposited into the ZRX Vault. Unstake to
retrieve the ZRX. Stake is in the 'Active' status.
:param amount: of ZRX to stake.
:param tx_params: transaction parameters
"""
(amount) = self.validate_and_normalize_inputs(amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(amount).transact(tx_params.as_dict())
def build_transaction(
self, amount: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(amount) = self.validate_and_normalize_inputs(amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(amount).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, amount: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(amount) = self.validate_and_normalize_inputs(amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(amount).estimateGas(tx_params.as_dict())
class StakingContractMethod(ContractMethod):
"""Various interfaces to the stakingContract method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
class UnstakeMethod(ContractMethod):
"""Various interfaces to the unstake method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, amount: int):
"""Validate the inputs to the unstake method."""
self.validator.assert_valid(
method_name="unstake",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return amount
def call(self, amount: int, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Unstake. Tokens are withdrawn from the ZRX Vault and returned to the
staker. Stake must be in the 'undelegated' status in both the current
and next epoch in order to be unstaked.
:param amount: of ZRX to unstake.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(amount) = self.validate_and_normalize_inputs(amount)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(amount).call(tx_params.as_dict())
def send_transaction(
self, amount: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Unstake. Tokens are withdrawn from the ZRX Vault and returned to the
staker. Stake must be in the 'undelegated' status in both the current
and next epoch in order to be unstaked.
:param amount: of ZRX to unstake.
:param tx_params: transaction parameters
"""
(amount) = self.validate_and_normalize_inputs(amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(amount).transact(tx_params.as_dict())
def build_transaction(
self, amount: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(amount) = self.validate_and_normalize_inputs(amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(amount).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, amount: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(amount) = self.validate_and_normalize_inputs(amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(amount).estimateGas(tx_params.as_dict())
class ValidExchangesMethod(ContractMethod):
"""Various interfaces to the validExchanges method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the validExchanges method."""
self.validator.assert_valid(
method_name="validExchanges",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class WethReservedForPoolRewardsMethod(ContractMethod):
"""Various interfaces to the wethReservedForPoolRewards method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class WithdrawDelegatorRewardsMethod(ContractMethod):
"""Various interfaces to the withdrawDelegatorRewards method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, pool_id: Union[bytes, str]):
"""Validate the inputs to the withdrawDelegatorRewards method."""
self.validator.assert_valid(
method_name="withdrawDelegatorRewards",
parameter_name="poolId",
argument_value=pool_id,
)
return pool_id
def call(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Withdraws the caller's WETH rewards that have accumulated until the
last epoch.
:param poolId: Unique id of pool.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(pool_id).call(tx_params.as_dict())
def send_transaction(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Withdraws the caller's WETH rewards that have accumulated until the
last epoch.
:param poolId: Unique id of pool.
:param tx_params: transaction parameters
"""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).transact(tx_params.as_dict())
def build_transaction(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, pool_id: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(pool_id) = self.validate_and_normalize_inputs(pool_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(pool_id).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class Staking:
"""Wrapper class for Staking Solidity contract."""
add_authorized_address: AddAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`AddAuthorizedAddressMethod`.
"""
add_exchange_address: AddExchangeAddressMethod
"""Constructor-initialized instance of
:class:`AddExchangeAddressMethod`.
"""
aggregated_stats_by_epoch: AggregatedStatsByEpochMethod
"""Constructor-initialized instance of
:class:`AggregatedStatsByEpochMethod`.
"""
authorities: AuthoritiesMethod
"""Constructor-initialized instance of
:class:`AuthoritiesMethod`.
"""
authorized: AuthorizedMethod
"""Constructor-initialized instance of
:class:`AuthorizedMethod`.
"""
cobb_douglas_alpha_denominator: CobbDouglasAlphaDenominatorMethod
"""Constructor-initialized instance of
:class:`CobbDouglasAlphaDenominatorMethod`.
"""
cobb_douglas_alpha_numerator: CobbDouglasAlphaNumeratorMethod
"""Constructor-initialized instance of
:class:`CobbDouglasAlphaNumeratorMethod`.
"""
compute_reward_balance_of_delegator: ComputeRewardBalanceOfDelegatorMethod
"""Constructor-initialized instance of
:class:`ComputeRewardBalanceOfDelegatorMethod`.
"""
compute_reward_balance_of_operator: ComputeRewardBalanceOfOperatorMethod
"""Constructor-initialized instance of
:class:`ComputeRewardBalanceOfOperatorMethod`.
"""
create_staking_pool: CreateStakingPoolMethod
"""Constructor-initialized instance of
:class:`CreateStakingPoolMethod`.
"""
current_epoch: CurrentEpochMethod
"""Constructor-initialized instance of
:class:`CurrentEpochMethod`.
"""
current_epoch_start_time_in_seconds: CurrentEpochStartTimeInSecondsMethod
"""Constructor-initialized instance of
:class:`CurrentEpochStartTimeInSecondsMethod`.
"""
decrease_staking_pool_operator_share: DecreaseStakingPoolOperatorShareMethod
"""Constructor-initialized instance of
:class:`DecreaseStakingPoolOperatorShareMethod`.
"""
end_epoch: EndEpochMethod
"""Constructor-initialized instance of
:class:`EndEpochMethod`.
"""
epoch_duration_in_seconds: EpochDurationInSecondsMethod
"""Constructor-initialized instance of
:class:`EpochDurationInSecondsMethod`.
"""
finalize_pool: FinalizePoolMethod
"""Constructor-initialized instance of
:class:`FinalizePoolMethod`.
"""
get_authorized_addresses: GetAuthorizedAddressesMethod
"""Constructor-initialized instance of
:class:`GetAuthorizedAddressesMethod`.
"""
get_current_epoch_earliest_end_time_in_seconds: GetCurrentEpochEarliestEndTimeInSecondsMethod
"""Constructor-initialized instance of
:class:`GetCurrentEpochEarliestEndTimeInSecondsMethod`.
"""
get_global_stake_by_status: GetGlobalStakeByStatusMethod
"""Constructor-initialized instance of
:class:`GetGlobalStakeByStatusMethod`.
"""
get_owner_stake_by_status: GetOwnerStakeByStatusMethod
"""Constructor-initialized instance of
:class:`GetOwnerStakeByStatusMethod`.
"""
get_params: GetParamsMethod
"""Constructor-initialized instance of
:class:`GetParamsMethod`.
"""
get_stake_delegated_to_pool_by_owner: GetStakeDelegatedToPoolByOwnerMethod
"""Constructor-initialized instance of
:class:`GetStakeDelegatedToPoolByOwnerMethod`.
"""
get_staking_pool: GetStakingPoolMethod
"""Constructor-initialized instance of
:class:`GetStakingPoolMethod`.
"""
get_staking_pool_stats_this_epoch: GetStakingPoolStatsThisEpochMethod
"""Constructor-initialized instance of
:class:`GetStakingPoolStatsThisEpochMethod`.
"""
get_total_stake: GetTotalStakeMethod
"""Constructor-initialized instance of
:class:`GetTotalStakeMethod`.
"""
get_total_stake_delegated_to_pool: GetTotalStakeDelegatedToPoolMethod
"""Constructor-initialized instance of
:class:`GetTotalStakeDelegatedToPoolMethod`.
"""
get_weth_contract: GetWethContractMethod
"""Constructor-initialized instance of
:class:`GetWethContractMethod`.
"""
get_zrx_vault: GetZrxVaultMethod
"""Constructor-initialized instance of
:class:`GetZrxVaultMethod`.
"""
init: InitMethod
"""Constructor-initialized instance of
:class:`InitMethod`.
"""
join_staking_pool_as_maker: JoinStakingPoolAsMakerMethod
"""Constructor-initialized instance of
:class:`JoinStakingPoolAsMakerMethod`.
"""
last_pool_id: LastPoolIdMethod
"""Constructor-initialized instance of
:class:`LastPoolIdMethod`.
"""
minimum_pool_stake: MinimumPoolStakeMethod
"""Constructor-initialized instance of
:class:`MinimumPoolStakeMethod`.
"""
move_stake: MoveStakeMethod
"""Constructor-initialized instance of
:class:`MoveStakeMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
pay_protocol_fee: PayProtocolFeeMethod
"""Constructor-initialized instance of
:class:`PayProtocolFeeMethod`.
"""
pool_id_by_maker: PoolIdByMakerMethod
"""Constructor-initialized instance of
:class:`PoolIdByMakerMethod`.
"""
pool_stats_by_epoch: PoolStatsByEpochMethod
"""Constructor-initialized instance of
:class:`PoolStatsByEpochMethod`.
"""
remove_authorized_address: RemoveAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressMethod`.
"""
remove_authorized_address_at_index: RemoveAuthorizedAddressAtIndexMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressAtIndexMethod`.
"""
remove_exchange_address: RemoveExchangeAddressMethod
"""Constructor-initialized instance of
:class:`RemoveExchangeAddressMethod`.
"""
reward_delegated_stake_weight: RewardDelegatedStakeWeightMethod
"""Constructor-initialized instance of
:class:`RewardDelegatedStakeWeightMethod`.
"""
rewards_by_pool_id: RewardsByPoolIdMethod
"""Constructor-initialized instance of
:class:`RewardsByPoolIdMethod`.
"""
set_params: SetParamsMethod
"""Constructor-initialized instance of
:class:`SetParamsMethod`.
"""
stake: StakeMethod
"""Constructor-initialized instance of
:class:`StakeMethod`.
"""
staking_contract: StakingContractMethod
"""Constructor-initialized instance of
:class:`StakingContractMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
unstake: UnstakeMethod
"""Constructor-initialized instance of
:class:`UnstakeMethod`.
"""
valid_exchanges: ValidExchangesMethod
"""Constructor-initialized instance of
:class:`ValidExchangesMethod`.
"""
weth_reserved_for_pool_rewards: WethReservedForPoolRewardsMethod
"""Constructor-initialized instance of
:class:`WethReservedForPoolRewardsMethod`.
"""
withdraw_delegator_rewards: WithdrawDelegatorRewardsMethod
"""Constructor-initialized instance of
:class:`WithdrawDelegatorRewardsMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: StakingValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = StakingValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=Staking.abi()
).functions
self.add_authorized_address = AddAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.addAuthorizedAddress,
validator,
)
self.add_exchange_address = AddExchangeAddressMethod(
web3_or_provider,
contract_address,
functions.addExchangeAddress,
validator,
)
self.aggregated_stats_by_epoch = AggregatedStatsByEpochMethod(
web3_or_provider,
contract_address,
functions.aggregatedStatsByEpoch,
validator,
)
self.authorities = AuthoritiesMethod(
web3_or_provider,
contract_address,
functions.authorities,
validator,
)
self.authorized = AuthorizedMethod(
web3_or_provider, contract_address, functions.authorized, validator
)
self.cobb_douglas_alpha_denominator = CobbDouglasAlphaDenominatorMethod(
web3_or_provider,
contract_address,
functions.cobbDouglasAlphaDenominator,
)
self.cobb_douglas_alpha_numerator = CobbDouglasAlphaNumeratorMethod(
web3_or_provider,
contract_address,
functions.cobbDouglasAlphaNumerator,
)
self.compute_reward_balance_of_delegator = ComputeRewardBalanceOfDelegatorMethod(
web3_or_provider,
contract_address,
functions.computeRewardBalanceOfDelegator,
validator,
)
self.compute_reward_balance_of_operator = ComputeRewardBalanceOfOperatorMethod(
web3_or_provider,
contract_address,
functions.computeRewardBalanceOfOperator,
validator,
)
self.create_staking_pool = CreateStakingPoolMethod(
web3_or_provider,
contract_address,
functions.createStakingPool,
validator,
)
self.current_epoch = CurrentEpochMethod(
web3_or_provider, contract_address, functions.currentEpoch
)
self.current_epoch_start_time_in_seconds = CurrentEpochStartTimeInSecondsMethod(
web3_or_provider,
contract_address,
functions.currentEpochStartTimeInSeconds,
)
self.decrease_staking_pool_operator_share = DecreaseStakingPoolOperatorShareMethod(
web3_or_provider,
contract_address,
functions.decreaseStakingPoolOperatorShare,
validator,
)
self.end_epoch = EndEpochMethod(
web3_or_provider, contract_address, functions.endEpoch
)
self.epoch_duration_in_seconds = EpochDurationInSecondsMethod(
web3_or_provider,
contract_address,
functions.epochDurationInSeconds,
)
self.finalize_pool = FinalizePoolMethod(
web3_or_provider,
contract_address,
functions.finalizePool,
validator,
)
self.get_authorized_addresses = GetAuthorizedAddressesMethod(
web3_or_provider,
contract_address,
functions.getAuthorizedAddresses,
)
self.get_current_epoch_earliest_end_time_in_seconds = GetCurrentEpochEarliestEndTimeInSecondsMethod(
web3_or_provider,
contract_address,
functions.getCurrentEpochEarliestEndTimeInSeconds,
)
self.get_global_stake_by_status = GetGlobalStakeByStatusMethod(
web3_or_provider,
contract_address,
functions.getGlobalStakeByStatus,
validator,
)
self.get_owner_stake_by_status = GetOwnerStakeByStatusMethod(
web3_or_provider,
contract_address,
functions.getOwnerStakeByStatus,
validator,
)
self.get_params = GetParamsMethod(
web3_or_provider, contract_address, functions.getParams
)
self.get_stake_delegated_to_pool_by_owner = GetStakeDelegatedToPoolByOwnerMethod(
web3_or_provider,
contract_address,
functions.getStakeDelegatedToPoolByOwner,
validator,
)
self.get_staking_pool = GetStakingPoolMethod(
web3_or_provider,
contract_address,
functions.getStakingPool,
validator,
)
self.get_staking_pool_stats_this_epoch = GetStakingPoolStatsThisEpochMethod(
web3_or_provider,
contract_address,
functions.getStakingPoolStatsThisEpoch,
validator,
)
self.get_total_stake = GetTotalStakeMethod(
web3_or_provider,
contract_address,
functions.getTotalStake,
validator,
)
self.get_total_stake_delegated_to_pool = GetTotalStakeDelegatedToPoolMethod(
web3_or_provider,
contract_address,
functions.getTotalStakeDelegatedToPool,
validator,
)
self.get_weth_contract = GetWethContractMethod(
web3_or_provider, contract_address, functions.getWethContract
)
self.get_zrx_vault = GetZrxVaultMethod(
web3_or_provider, contract_address, functions.getZrxVault
)
self.init = InitMethod(
web3_or_provider, contract_address, functions.init
)
self.join_staking_pool_as_maker = JoinStakingPoolAsMakerMethod(
web3_or_provider,
contract_address,
functions.joinStakingPoolAsMaker,
validator,
)
self.last_pool_id = LastPoolIdMethod(
web3_or_provider, contract_address, functions.lastPoolId
)
self.minimum_pool_stake = MinimumPoolStakeMethod(
web3_or_provider, contract_address, functions.minimumPoolStake
)
self.move_stake = MoveStakeMethod(
web3_or_provider, contract_address, functions.moveStake, validator
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.pay_protocol_fee = PayProtocolFeeMethod(
web3_or_provider,
contract_address,
functions.payProtocolFee,
validator,
)
self.pool_id_by_maker = PoolIdByMakerMethod(
web3_or_provider,
contract_address,
functions.poolIdByMaker,
validator,
)
self.pool_stats_by_epoch = PoolStatsByEpochMethod(
web3_or_provider,
contract_address,
functions.poolStatsByEpoch,
validator,
)
self.remove_authorized_address = RemoveAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddress,
validator,
)
self.remove_authorized_address_at_index = RemoveAuthorizedAddressAtIndexMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddressAtIndex,
validator,
)
self.remove_exchange_address = RemoveExchangeAddressMethod(
web3_or_provider,
contract_address,
functions.removeExchangeAddress,
validator,
)
self.reward_delegated_stake_weight = RewardDelegatedStakeWeightMethod(
web3_or_provider,
contract_address,
functions.rewardDelegatedStakeWeight,
)
self.rewards_by_pool_id = RewardsByPoolIdMethod(
web3_or_provider,
contract_address,
functions.rewardsByPoolId,
validator,
)
self.set_params = SetParamsMethod(
web3_or_provider, contract_address, functions.setParams, validator
)
self.stake = StakeMethod(
web3_or_provider, contract_address, functions.stake, validator
)
self.staking_contract = StakingContractMethod(
web3_or_provider, contract_address, functions.stakingContract
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
self.unstake = UnstakeMethod(
web3_or_provider, contract_address, functions.unstake, validator
)
self.valid_exchanges = ValidExchangesMethod(
web3_or_provider,
contract_address,
functions.validExchanges,
validator,
)
self.weth_reserved_for_pool_rewards = WethReservedForPoolRewardsMethod(
web3_or_provider,
contract_address,
functions.wethReservedForPoolRewards,
)
self.withdraw_delegator_rewards = WithdrawDelegatorRewardsMethod(
web3_or_provider,
contract_address,
functions.withdrawDelegatorRewards,
validator,
)
def get_authorized_address_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressAdded event.
:param tx_hash: hash of transaction emitting AuthorizedAddressAdded
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.AuthorizedAddressAdded()
.processReceipt(tx_receipt)
)
def get_authorized_address_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressRemoved event.
:param tx_hash: hash of transaction emitting AuthorizedAddressRemoved
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.AuthorizedAddressRemoved()
.processReceipt(tx_receipt)
)
def get_epoch_ended_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for EpochEnded event.
:param tx_hash: hash of transaction emitting EpochEnded event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.EpochEnded()
.processReceipt(tx_receipt)
)
def get_epoch_finalized_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for EpochFinalized event.
:param tx_hash: hash of transaction emitting EpochFinalized event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.EpochFinalized()
.processReceipt(tx_receipt)
)
def get_exchange_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ExchangeAdded event.
:param tx_hash: hash of transaction emitting ExchangeAdded event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.ExchangeAdded()
.processReceipt(tx_receipt)
)
def get_exchange_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ExchangeRemoved event.
:param tx_hash: hash of transaction emitting ExchangeRemoved event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.ExchangeRemoved()
.processReceipt(tx_receipt)
)
def get_maker_staking_pool_set_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for MakerStakingPoolSet event.
:param tx_hash: hash of transaction emitting MakerStakingPoolSet event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.MakerStakingPoolSet()
.processReceipt(tx_receipt)
)
def get_move_stake_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for MoveStake event.
:param tx_hash: hash of transaction emitting MoveStake event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.MoveStake()
.processReceipt(tx_receipt)
)
def get_operator_share_decreased_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for OperatorShareDecreased event.
:param tx_hash: hash of transaction emitting OperatorShareDecreased
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.OperatorShareDecreased()
.processReceipt(tx_receipt)
)
def get_ownership_transferred_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for OwnershipTransferred event.
:param tx_hash: hash of transaction emitting OwnershipTransferred event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.OwnershipTransferred()
.processReceipt(tx_receipt)
)
def get_params_set_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ParamsSet event.
:param tx_hash: hash of transaction emitting ParamsSet event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.ParamsSet()
.processReceipt(tx_receipt)
)
def get_rewards_paid_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for RewardsPaid event.
:param tx_hash: hash of transaction emitting RewardsPaid event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.RewardsPaid()
.processReceipt(tx_receipt)
)
def get_stake_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Stake event.
:param tx_hash: hash of transaction emitting Stake event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.Stake()
.processReceipt(tx_receipt)
)
def get_staking_pool_created_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for StakingPoolCreated event.
:param tx_hash: hash of transaction emitting StakingPoolCreated event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.StakingPoolCreated()
.processReceipt(tx_receipt)
)
def get_staking_pool_earned_rewards_in_epoch_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for StakingPoolEarnedRewardsInEpoch event.
:param tx_hash: hash of transaction emitting
StakingPoolEarnedRewardsInEpoch event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.StakingPoolEarnedRewardsInEpoch()
.processReceipt(tx_receipt)
)
def get_unstake_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Unstake event.
:param tx_hash: hash of transaction emitting Unstake event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Staking.abi(),
)
.events.Unstake()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"address","name":"wethAddress","type":"address"},{"internalType":"address","name":"zrxVaultAddress","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"numPoolsToFinalize","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardsAvailable","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalFeesCollected","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalWeightedStake","type":"uint256"}],"name":"EpochEnded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardsPaid","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardsRemaining","type":"uint256"}],"name":"EpochFinalized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"exchangeAddress","type":"address"}],"name":"ExchangeAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"exchangeAddress","type":"address"}],"name":"ExchangeRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"makerAddress","type":"address"},{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"MakerStakingPoolSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"staker","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint8","name":"fromStatus","type":"uint8"},{"indexed":true,"internalType":"bytes32","name":"fromPool","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"toStatus","type":"uint8"},{"indexed":true,"internalType":"bytes32","name":"toPool","type":"bytes32"}],"name":"MoveStake","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"uint32","name":"oldOperatorShare","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"newOperatorShare","type":"uint32"}],"name":"OperatorShareDecreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"epochDurationInSeconds","type":"uint256"},{"indexed":false,"internalType":"uint32","name":"rewardDelegatedStakeWeight","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"minimumPoolStake","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"cobbDouglasAlphaNumerator","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"cobbDouglasAlphaDenominator","type":"uint256"}],"name":"ParamsSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"operatorReward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"membersReward","type":"uint256"}],"name":"RewardsPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"staker","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Stake","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"uint32","name":"operatorShare","type":"uint32"}],"name":"StakingPoolCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"StakingPoolEarnedRewardsInEpoch","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"staker","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Unstake","type":"event"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"addAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"addExchangeAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"aggregatedStatsByEpoch","outputs":[{"internalType":"uint256","name":"rewardsAvailable","type":"uint256"},{"internalType":"uint256","name":"numPoolsToFinalize","type":"uint256"},{"internalType":"uint256","name":"totalFeesCollected","type":"uint256"},{"internalType":"uint256","name":"totalWeightedStake","type":"uint256"},{"internalType":"uint256","name":"totalRewardsFinalized","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"authorities","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"authorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"cobbDouglasAlphaDenominator","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"cobbDouglasAlphaNumerator","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"address","name":"member","type":"address"}],"name":"computeRewardBalanceOfDelegator","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"computeRewardBalanceOfOperator","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint32","name":"operatorShare","type":"uint32"},{"internalType":"bool","name":"addOperatorAsMaker","type":"bool"}],"name":"createStakingPool","outputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"currentEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"currentEpochStartTimeInSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"uint32","name":"newOperatorShare","type":"uint32"}],"name":"decreaseStakingPoolOperatorShare","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"endEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"epochDurationInSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"finalizePool","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getAuthorizedAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCurrentEpochEarliestEndTimeInSeconds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"enum IStructs.StakeStatus","name":"stakeStatus","type":"uint8"}],"name":"getGlobalStakeByStatus","outputs":[{"components":[{"internalType":"uint64","name":"currentEpoch","type":"uint64"},{"internalType":"uint96","name":"currentEpochBalance","type":"uint96"},{"internalType":"uint96","name":"nextEpochBalance","type":"uint96"}],"internalType":"struct IStructs.StoredBalance","name":"balance","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"staker","type":"address"},{"internalType":"enum IStructs.StakeStatus","name":"stakeStatus","type":"uint8"}],"name":"getOwnerStakeByStatus","outputs":[{"components":[{"internalType":"uint64","name":"currentEpoch","type":"uint64"},{"internalType":"uint96","name":"currentEpochBalance","type":"uint96"},{"internalType":"uint96","name":"nextEpochBalance","type":"uint96"}],"internalType":"struct IStructs.StoredBalance","name":"balance","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getParams","outputs":[{"internalType":"uint256","name":"_epochDurationInSeconds","type":"uint256"},{"internalType":"uint32","name":"_rewardDelegatedStakeWeight","type":"uint32"},{"internalType":"uint256","name":"_minimumPoolStake","type":"uint256"},{"internalType":"uint32","name":"_cobbDouglasAlphaNumerator","type":"uint32"},{"internalType":"uint32","name":"_cobbDouglasAlphaDenominator","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"staker","type":"address"},{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"getStakeDelegatedToPoolByOwner","outputs":[{"components":[{"internalType":"uint64","name":"currentEpoch","type":"uint64"},{"internalType":"uint96","name":"currentEpochBalance","type":"uint96"},{"internalType":"uint96","name":"nextEpochBalance","type":"uint96"}],"internalType":"struct IStructs.StoredBalance","name":"balance","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"getStakingPool","outputs":[{"components":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint32","name":"operatorShare","type":"uint32"}],"internalType":"struct IStructs.Pool","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"getStakingPoolStatsThisEpoch","outputs":[{"components":[{"internalType":"uint256","name":"feesCollected","type":"uint256"},{"internalType":"uint256","name":"weightedStake","type":"uint256"},{"internalType":"uint256","name":"membersStake","type":"uint256"}],"internalType":"struct IStructs.PoolStats","name":"","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"staker","type":"address"}],"name":"getTotalStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"getTotalStakeDelegatedToPool","outputs":[{"components":[{"internalType":"uint64","name":"currentEpoch","type":"uint64"},{"internalType":"uint96","name":"currentEpochBalance","type":"uint96"},{"internalType":"uint96","name":"nextEpochBalance","type":"uint96"}],"internalType":"struct IStructs.StoredBalance","name":"balance","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getWethContract","outputs":[{"internalType":"contract IEtherToken","name":"wethContract","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getZrxVault","outputs":[{"internalType":"contract IZrxVault","name":"zrxVault","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"init","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"joinStakingPoolAsMaker","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"lastPoolId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"minimumPoolStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"enum IStructs.StakeStatus","name":"status","type":"uint8"},{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"internalType":"struct IStructs.StakeInfo","name":"from","type":"tuple"},{"components":[{"internalType":"enum IStructs.StakeStatus","name":"status","type":"uint8"},{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"internalType":"struct IStructs.StakeInfo","name":"to","type":"tuple"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"moveStake","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"payerAddress","type":"address"},{"internalType":"uint256","name":"protocolFee","type":"uint256"}],"name":"payProtocolFee","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"poolIdByMaker","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"index_0","type":"bytes32"},{"internalType":"uint256","name":"index_1","type":"uint256"}],"name":"poolStatsByEpoch","outputs":[{"internalType":"uint256","name":"feesCollected","type":"uint256"},{"internalType":"uint256","name":"weightedStake","type":"uint256"},{"internalType":"uint256","name":"membersStake","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"removeAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"removeAuthorizedAddressAtIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"removeExchangeAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"rewardDelegatedStakeWeight","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"index_0","type":"bytes32"}],"name":"rewardsByPoolId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_epochDurationInSeconds","type":"uint256"},{"internalType":"uint32","name":"_rewardDelegatedStakeWeight","type":"uint32"},{"internalType":"uint256","name":"_minimumPoolStake","type":"uint256"},{"internalType":"uint32","name":"_cobbDouglasAlphaNumerator","type":"uint32"},{"internalType":"uint32","name":"_cobbDouglasAlphaDenominator","type":"uint32"}],"name":"setParams","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"stakingContract","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"unstake","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"validExchanges","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"wethReservedForPoolRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"withdrawDelegatorRewards","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/staking/__init__.py | __init__.py |
"""Generated wrapper for ERC721Proxy Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ERC721Proxy below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ERC721ProxyValidator,
)
except ImportError:
class ERC721ProxyValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class AddAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the addAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the addAuthorizedAddress method."""
self.validator.assert_valid(
method_name="addAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class AuthoritiesMethod(ContractMethod):
"""Various interfaces to the authorities method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the authorities method."""
self.validator.assert_valid(
method_name="authorities",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class RemoveAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the removeAuthorizedAddress method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressAtIndexMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddressAtIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str, index: int):
"""Validate the inputs to the removeAuthorizedAddressAtIndex method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="index",
argument_value=index,
)
# safeguard against fractional inputs
index = int(index)
return (target, index)
def call(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target, index).call(tx_params.as_dict())
def send_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).transact(
tx_params.as_dict()
)
def build_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).estimateGas(
tx_params.as_dict()
)
class GetProxyIdMethod(ContractMethod):
"""Various interfaces to the getProxyId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Gets the proxy id associated with the proxy address.
:param tx_params: transaction parameters
:returns: Proxy id.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AuthorizedMethod(ContractMethod):
"""Various interfaces to the authorized method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the authorized method."""
self.validator.assert_valid(
method_name="authorized",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class GetAuthorizedAddressesMethod(ContractMethod):
"""Various interfaces to the getAuthorizedAddresses method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Gets all authorized addresses.
:param tx_params: transaction parameters
:returns: Array of authorized addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ERC721Proxy:
"""Wrapper class for ERC721Proxy Solidity contract."""
add_authorized_address: AddAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`AddAuthorizedAddressMethod`.
"""
authorities: AuthoritiesMethod
"""Constructor-initialized instance of
:class:`AuthoritiesMethod`.
"""
remove_authorized_address: RemoveAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
remove_authorized_address_at_index: RemoveAuthorizedAddressAtIndexMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressAtIndexMethod`.
"""
get_proxy_id: GetProxyIdMethod
"""Constructor-initialized instance of
:class:`GetProxyIdMethod`.
"""
authorized: AuthorizedMethod
"""Constructor-initialized instance of
:class:`AuthorizedMethod`.
"""
get_authorized_addresses: GetAuthorizedAddressesMethod
"""Constructor-initialized instance of
:class:`GetAuthorizedAddressesMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ERC721ProxyValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ERC721ProxyValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=ERC721Proxy.abi(),
).functions
self.add_authorized_address = AddAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.addAuthorizedAddress,
validator,
)
self.authorities = AuthoritiesMethod(
web3_or_provider,
contract_address,
functions.authorities,
validator,
)
self.remove_authorized_address = RemoveAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddress,
validator,
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.remove_authorized_address_at_index = RemoveAuthorizedAddressAtIndexMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddressAtIndex,
validator,
)
self.get_proxy_id = GetProxyIdMethod(
web3_or_provider, contract_address, functions.getProxyId
)
self.authorized = AuthorizedMethod(
web3_or_provider, contract_address, functions.authorized, validator
)
self.get_authorized_addresses = GetAuthorizedAddressesMethod(
web3_or_provider,
contract_address,
functions.getAuthorizedAddresses,
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
def get_authorized_address_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressAdded event.
:param tx_hash: hash of transaction emitting AuthorizedAddressAdded
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC721Proxy.abi(),
)
.events.AuthorizedAddressAdded()
.processReceipt(tx_receipt)
)
def get_authorized_address_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressRemoved event.
:param tx_hash: hash of transaction emitting AuthorizedAddressRemoved
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC721Proxy.abi(),
)
.events.AuthorizedAddressRemoved()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"addAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"authorities","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"removeAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"removeAuthorizedAddressAtIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getProxyId","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"authorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAuthorizedAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"payable":false,"stateMutability":"nonpayable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressRemoved","type":"event"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/erc721_proxy/__init__.py | __init__.py |
"""Generated wrapper for IValidator Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for IValidator below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
IValidatorValidator,
)
except ImportError:
class IValidatorValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class IsValidSignatureMethod(ContractMethod):
"""Various interfaces to the isValidSignature method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
_hash: Union[bytes, str],
signer_address: str,
signature: Union[bytes, str],
):
"""Validate the inputs to the isValidSignature method."""
self.validator.assert_valid(
method_name="isValidSignature",
parameter_name="hash",
argument_value=_hash,
)
self.validator.assert_valid(
method_name="isValidSignature",
parameter_name="signerAddress",
argument_value=signer_address,
)
signer_address = self.validate_and_checksum_address(signer_address)
self.validator.assert_valid(
method_name="isValidSignature",
parameter_name="signature",
argument_value=signature,
)
return (_hash, signer_address, signature)
def call(
self,
_hash: Union[bytes, str],
signer_address: str,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Verifies that a signature is valid.
:param hash: Message hash that is signed.
:param signature: Proof of signing.
:param signerAddress: Address that should have signed the given hash.
:param tx_params: transaction parameters
:returns: Magic bytes4 value if the signature is valid. Magic value is
bytes4(keccak256("isValidValidatorSignature(address,bytes32,address,by-
tes)"))
"""
(
_hash,
signer_address,
signature,
) = self.validate_and_normalize_inputs(
_hash, signer_address, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
_hash, signer_address, signature
).call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(
self,
_hash: Union[bytes, str],
signer_address: str,
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
_hash,
signer_address,
signature,
) = self.validate_and_normalize_inputs(
_hash, signer_address, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_hash, signer_address, signature
).estimateGas(tx_params.as_dict())
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class IValidator:
"""Wrapper class for IValidator Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
is_valid_signature: IsValidSignatureMethod
"""Constructor-initialized instance of
:class:`IsValidSignatureMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: IValidatorValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = IValidatorValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=IValidator.abi()
).functions
self.is_valid_signature = IsValidSignatureMethod(
web3_or_provider,
contract_address,
functions.isValidSignature,
validator,
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":true,"inputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"address","name":"signerAddress","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"isValidSignature","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"view","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/i_validator/__init__.py | __init__.py |
"""Generated wrapper for StaticCallProxy Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for StaticCallProxy below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
StaticCallProxyValidator,
)
except ImportError:
class StaticCallProxyValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, asset_data: Union[bytes, str], _from: str, to: str, amount: int
):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="assetData",
argument_value=asset_data,
)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom", parameter_name="to", argument_value=to,
)
to = self.validate_and_checksum_address(to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return (asset_data, _from, to, amount)
def call(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Makes a staticcall to a target address and verifies that the data
returned matches the expected return data.
:param amount: This value is ignored.
:param assetData: Byte array encoded with staticCallTarget,
staticCallData, and expectedCallResultHash
:param from: This value is ignored.
:param to: This value is ignored.
:param tx_params: transaction parameters
"""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_data, _from, to, amount).call(
tx_params.as_dict()
)
def estimate_gas(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, _from, to, amount
).estimateGas(tx_params.as_dict())
class GetProxyIdMethod(ContractMethod):
"""Various interfaces to the getProxyId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Gets the proxy id associated with the proxy address.
:param tx_params: transaction parameters
:returns: Proxy id.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class StaticCallProxy:
"""Wrapper class for StaticCallProxy Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
get_proxy_id: GetProxyIdMethod
"""Constructor-initialized instance of
:class:`GetProxyIdMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: StaticCallProxyValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = StaticCallProxyValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=StaticCallProxy.abi(),
).functions
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.get_proxy_id = GetProxyIdMethod(
web3_or_provider, contract_address, functions.getProxyId
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":true,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getProxyId","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"pure","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/static_call_proxy/__init__.py | __init__.py |
"""Generated wrapper for MultiAssetProxy Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for MultiAssetProxy below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
MultiAssetProxyValidator,
)
except ImportError:
class MultiAssetProxyValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class AssetProxiesMethod(ContractMethod):
"""Various interfaces to the assetProxies method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: Union[bytes, str]):
"""Validate the inputs to the assetProxies method."""
self.validator.assert_valid(
method_name="assetProxies",
parameter_name="index_0",
argument_value=index_0,
)
return index_0
def call(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: Union[bytes, str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class AddAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the addAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the addAuthorizedAddress method."""
self.validator.assert_valid(
method_name="addAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class AuthoritiesMethod(ContractMethod):
"""Various interfaces to the authorities method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the authorities method."""
self.validator.assert_valid(
method_name="authorities",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class GetAssetProxyMethod(ContractMethod):
"""Various interfaces to the getAssetProxy method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_proxy_id: Union[bytes, str]):
"""Validate the inputs to the getAssetProxy method."""
self.validator.assert_valid(
method_name="getAssetProxy",
parameter_name="assetProxyId",
argument_value=asset_proxy_id,
)
return asset_proxy_id
def call(
self,
asset_proxy_id: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> str:
"""Execute underlying contract method via eth_call.
Gets an asset proxy.
:param assetProxyId: Id of the asset proxy.
:param tx_params: transaction parameters
:returns: The asset proxy registered to assetProxyId. Returns 0x0 if no
proxy is registered.
"""
(asset_proxy_id) = self.validate_and_normalize_inputs(asset_proxy_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(asset_proxy_id).call(
tx_params.as_dict()
)
return str(returned)
def estimate_gas(
self,
asset_proxy_id: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_proxy_id) = self.validate_and_normalize_inputs(asset_proxy_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_proxy_id).estimateGas(
tx_params.as_dict()
)
class RemoveAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the removeAuthorizedAddress method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressAtIndexMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddressAtIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str, index: int):
"""Validate the inputs to the removeAuthorizedAddressAtIndex method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="index",
argument_value=index,
)
# safeguard against fractional inputs
index = int(index)
return (target, index)
def call(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target, index).call(tx_params.as_dict())
def send_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).transact(
tx_params.as_dict()
)
def build_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).estimateGas(
tx_params.as_dict()
)
class GetProxyIdMethod(ContractMethod):
"""Various interfaces to the getProxyId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Gets the proxy id associated with the proxy address.
:param tx_params: transaction parameters
:returns: Proxy id.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AuthorizedMethod(ContractMethod):
"""Various interfaces to the authorized method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the authorized method."""
self.validator.assert_valid(
method_name="authorized",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class RegisterAssetProxyMethod(ContractMethod):
"""Various interfaces to the registerAssetProxy method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_proxy: str):
"""Validate the inputs to the registerAssetProxy method."""
self.validator.assert_valid(
method_name="registerAssetProxy",
parameter_name="assetProxy",
argument_value=asset_proxy,
)
asset_proxy = self.validate_and_checksum_address(asset_proxy)
return asset_proxy
def call(
self, asset_proxy: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Registers an asset proxy to its asset proxy id. Once an asset proxy is
registered, it cannot be unregistered.
:param assetProxy: Address of new asset proxy to register.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(asset_proxy) = self.validate_and_normalize_inputs(asset_proxy)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_proxy).call(tx_params.as_dict())
def send_transaction(
self, asset_proxy: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Registers an asset proxy to its asset proxy id. Once an asset proxy is
registered, it cannot be unregistered.
:param assetProxy: Address of new asset proxy to register.
:param tx_params: transaction parameters
"""
(asset_proxy) = self.validate_and_normalize_inputs(asset_proxy)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_proxy).transact(
tx_params.as_dict()
)
def build_transaction(
self, asset_proxy: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(asset_proxy) = self.validate_and_normalize_inputs(asset_proxy)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_proxy).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, asset_proxy: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(asset_proxy) = self.validate_and_normalize_inputs(asset_proxy)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_proxy).estimateGas(
tx_params.as_dict()
)
class GetAuthorizedAddressesMethod(ContractMethod):
"""Various interfaces to the getAuthorizedAddresses method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Gets all authorized addresses.
:param tx_params: transaction parameters
:returns: Array of authorized addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class MultiAssetProxy:
"""Wrapper class for MultiAssetProxy Solidity contract."""
asset_proxies: AssetProxiesMethod
"""Constructor-initialized instance of
:class:`AssetProxiesMethod`.
"""
add_authorized_address: AddAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`AddAuthorizedAddressMethod`.
"""
authorities: AuthoritiesMethod
"""Constructor-initialized instance of
:class:`AuthoritiesMethod`.
"""
get_asset_proxy: GetAssetProxyMethod
"""Constructor-initialized instance of
:class:`GetAssetProxyMethod`.
"""
remove_authorized_address: RemoveAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
remove_authorized_address_at_index: RemoveAuthorizedAddressAtIndexMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressAtIndexMethod`.
"""
get_proxy_id: GetProxyIdMethod
"""Constructor-initialized instance of
:class:`GetProxyIdMethod`.
"""
authorized: AuthorizedMethod
"""Constructor-initialized instance of
:class:`AuthorizedMethod`.
"""
register_asset_proxy: RegisterAssetProxyMethod
"""Constructor-initialized instance of
:class:`RegisterAssetProxyMethod`.
"""
get_authorized_addresses: GetAuthorizedAddressesMethod
"""Constructor-initialized instance of
:class:`GetAuthorizedAddressesMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: MultiAssetProxyValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = MultiAssetProxyValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=MultiAssetProxy.abi(),
).functions
self.asset_proxies = AssetProxiesMethod(
web3_or_provider,
contract_address,
functions.assetProxies,
validator,
)
self.add_authorized_address = AddAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.addAuthorizedAddress,
validator,
)
self.authorities = AuthoritiesMethod(
web3_or_provider,
contract_address,
functions.authorities,
validator,
)
self.get_asset_proxy = GetAssetProxyMethod(
web3_or_provider,
contract_address,
functions.getAssetProxy,
validator,
)
self.remove_authorized_address = RemoveAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddress,
validator,
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.remove_authorized_address_at_index = RemoveAuthorizedAddressAtIndexMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddressAtIndex,
validator,
)
self.get_proxy_id = GetProxyIdMethod(
web3_or_provider, contract_address, functions.getProxyId
)
self.authorized = AuthorizedMethod(
web3_or_provider, contract_address, functions.authorized, validator
)
self.register_asset_proxy = RegisterAssetProxyMethod(
web3_or_provider,
contract_address,
functions.registerAssetProxy,
validator,
)
self.get_authorized_addresses = GetAuthorizedAddressesMethod(
web3_or_provider,
contract_address,
functions.getAuthorizedAddresses,
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
def get_authorized_address_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressAdded event.
:param tx_hash: hash of transaction emitting AuthorizedAddressAdded
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=MultiAssetProxy.abi(),
)
.events.AuthorizedAddressAdded()
.processReceipt(tx_receipt)
)
def get_authorized_address_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressRemoved event.
:param tx_hash: hash of transaction emitting AuthorizedAddressRemoved
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=MultiAssetProxy.abi(),
)
.events.AuthorizedAddressRemoved()
.processReceipt(tx_receipt)
)
def get_asset_proxy_registered_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AssetProxyRegistered event.
:param tx_hash: hash of transaction emitting AssetProxyRegistered event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=MultiAssetProxy.abi(),
)
.events.AssetProxyRegistered()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":true,"inputs":[{"internalType":"bytes4","name":"index_0","type":"bytes4"}],"name":"assetProxies","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"addAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"authorities","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes4","name":"assetProxyId","type":"bytes4"}],"name":"getAssetProxy","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"removeAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"removeAuthorizedAddressAtIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getProxyId","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"authorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"assetProxy","type":"address"}],"name":"registerAssetProxy","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getAuthorizedAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"payable":false,"stateMutability":"nonpayable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes4","name":"id","type":"bytes4"},{"indexed":false,"internalType":"address","name":"assetProxy","type":"address"}],"name":"AssetProxyRegistered","type":"event"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/multi_asset_proxy/__init__.py | __init__.py |
"""Generated wrapper for ERC20Proxy Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ERC20Proxy below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ERC20ProxyValidator,
)
except ImportError:
class ERC20ProxyValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class AddAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the addAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the addAuthorizedAddress method."""
self.validator.assert_valid(
method_name="addAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class AuthoritiesMethod(ContractMethod):
"""Various interfaces to the authorities method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the authorities method."""
self.validator.assert_valid(
method_name="authorities",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class RemoveAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the removeAuthorizedAddress method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressAtIndexMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddressAtIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str, index: int):
"""Validate the inputs to the removeAuthorizedAddressAtIndex method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="index",
argument_value=index,
)
# safeguard against fractional inputs
index = int(index)
return (target, index)
def call(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target, index).call(tx_params.as_dict())
def send_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).transact(
tx_params.as_dict()
)
def build_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).estimateGas(
tx_params.as_dict()
)
class GetProxyIdMethod(ContractMethod):
"""Various interfaces to the getProxyId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Gets the proxy id associated with the proxy address.
:param tx_params: transaction parameters
:returns: Proxy id.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AuthorizedMethod(ContractMethod):
"""Various interfaces to the authorized method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the authorized method."""
self.validator.assert_valid(
method_name="authorized",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class GetAuthorizedAddressesMethod(ContractMethod):
"""Various interfaces to the getAuthorizedAddresses method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Gets all authorized addresses.
:param tx_params: transaction parameters
:returns: Array of authorized addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ERC20Proxy:
"""Wrapper class for ERC20Proxy Solidity contract."""
add_authorized_address: AddAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`AddAuthorizedAddressMethod`.
"""
authorities: AuthoritiesMethod
"""Constructor-initialized instance of
:class:`AuthoritiesMethod`.
"""
remove_authorized_address: RemoveAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
remove_authorized_address_at_index: RemoveAuthorizedAddressAtIndexMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressAtIndexMethod`.
"""
get_proxy_id: GetProxyIdMethod
"""Constructor-initialized instance of
:class:`GetProxyIdMethod`.
"""
authorized: AuthorizedMethod
"""Constructor-initialized instance of
:class:`AuthorizedMethod`.
"""
get_authorized_addresses: GetAuthorizedAddressesMethod
"""Constructor-initialized instance of
:class:`GetAuthorizedAddressesMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ERC20ProxyValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ERC20ProxyValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=ERC20Proxy.abi()
).functions
self.add_authorized_address = AddAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.addAuthorizedAddress,
validator,
)
self.authorities = AuthoritiesMethod(
web3_or_provider,
contract_address,
functions.authorities,
validator,
)
self.remove_authorized_address = RemoveAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddress,
validator,
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.remove_authorized_address_at_index = RemoveAuthorizedAddressAtIndexMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddressAtIndex,
validator,
)
self.get_proxy_id = GetProxyIdMethod(
web3_or_provider, contract_address, functions.getProxyId
)
self.authorized = AuthorizedMethod(
web3_or_provider, contract_address, functions.authorized, validator
)
self.get_authorized_addresses = GetAuthorizedAddressesMethod(
web3_or_provider,
contract_address,
functions.getAuthorizedAddresses,
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
def get_authorized_address_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressAdded event.
:param tx_hash: hash of transaction emitting AuthorizedAddressAdded
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC20Proxy.abi(),
)
.events.AuthorizedAddressAdded()
.processReceipt(tx_receipt)
)
def get_authorized_address_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressRemoved event.
:param tx_hash: hash of transaction emitting AuthorizedAddressRemoved
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC20Proxy.abi(),
)
.events.AuthorizedAddressRemoved()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"addAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"authorities","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"removeAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"removeAuthorizedAddressAtIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getProxyId","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"authorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAuthorizedAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"payable":false,"stateMutability":"nonpayable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressRemoved","type":"event"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/erc20_proxy/__init__.py | __init__.py |
"""Generated wrapper for DummyERC20Token Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for DummyERC20Token below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
DummyERC20TokenValidator,
)
except ImportError:
class DummyERC20TokenValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class MaxMintAmountMethod(ContractMethod):
"""Various interfaces to the MAX_MINT_AMOUNT method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AllowanceMethod(ContractMethod):
"""Various interfaces to the allowance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str, _spender: str):
"""Validate the inputs to the allowance method."""
self.validator.assert_valid(
method_name="allowance",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
self.validator.assert_valid(
method_name="allowance",
parameter_name="_spender",
argument_value=_spender,
)
_spender = self.validate_and_checksum_address(_spender)
return (_owner, _spender)
def call(
self, _owner: str, _spender: str, tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param _owner: The address of the account owning tokens
:param _spender: The address of the account able to transfer the tokens
:param tx_params: transaction parameters
:returns: Amount of remaining tokens allowed to spent
"""
(_owner, _spender) = self.validate_and_normalize_inputs(
_owner, _spender
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner, _spender).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self, _owner: str, _spender: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner, _spender) = self.validate_and_normalize_inputs(
_owner, _spender
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner, _spender).estimateGas(
tx_params.as_dict()
)
class ApproveMethod(ContractMethod):
"""Various interfaces to the approve method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _spender: str, _value: int):
"""Validate the inputs to the approve method."""
self.validator.assert_valid(
method_name="approve",
parameter_name="_spender",
argument_value=_spender,
)
_spender = self.validate_and_checksum_address(_spender)
self.validator.assert_valid(
method_name="approve",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_spender, _value)
def call(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
`msg.sender` approves `_spender` to spend `_value` tokens
:param _spender: The address of the account able to transfer the tokens
:param _value: The amount of wei to be approved for transfer
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_spender, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
`msg.sender` approves `_spender` to spend `_value` tokens
:param _spender: The address of the account able to transfer the tokens
:param _value: The amount of wei to be approved for transfer
:param tx_params: transaction parameters
"""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _spender: str, _value: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_spender, _value) = self.validate_and_normalize_inputs(
_spender, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_spender, _value).estimateGas(
tx_params.as_dict()
)
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _owner: str):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="_owner",
argument_value=_owner,
)
_owner = self.validate_and_checksum_address(_owner)
return _owner
def call(self, _owner: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Query the balance of owner
:param _owner: The address from which the balance will be retrieved
:param tx_params: transaction parameters
:returns: Balance of owner
"""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_owner).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, _owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_owner) = self.validate_and_normalize_inputs(_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_owner).estimateGas(tx_params.as_dict())
class DecimalsMethod(ContractMethod):
"""Various interfaces to the decimals method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class MintMethod(ContractMethod):
"""Various interfaces to the mint method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _value: int):
"""Validate the inputs to the mint method."""
self.validator.assert_valid(
method_name="mint", parameter_name="_value", argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return _value
def call(self, _value: int, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Mints new tokens for sender
:param _value: Amount of tokens to mint
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_value) = self.validate_and_normalize_inputs(_value)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_value).call(tx_params.as_dict())
def send_transaction(
self, _value: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Mints new tokens for sender
:param _value: Amount of tokens to mint
:param tx_params: transaction parameters
"""
(_value) = self.validate_and_normalize_inputs(_value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_value).transact(tx_params.as_dict())
def build_transaction(
self, _value: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_value) = self.validate_and_normalize_inputs(_value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _value: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_value) = self.validate_and_normalize_inputs(_value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_value).estimateGas(tx_params.as_dict())
class NameMethod(ContractMethod):
"""Various interfaces to the name method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class SetBalanceMethod(ContractMethod):
"""Various interfaces to the setBalance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _target: str, _value: int):
"""Validate the inputs to the setBalance method."""
self.validator.assert_valid(
method_name="setBalance",
parameter_name="_target",
argument_value=_target,
)
_target = self.validate_and_checksum_address(_target)
self.validator.assert_valid(
method_name="setBalance",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_target, _value)
def call(
self, _target: str, _value: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Sets the balance of target address
:param _target: Address or which balance will be updated
:param _value: New balance of target address
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_target, _value) = self.validate_and_normalize_inputs(_target, _value)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_target, _value).call(tx_params.as_dict())
def send_transaction(
self, _target: str, _value: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Sets the balance of target address
:param _target: Address or which balance will be updated
:param _value: New balance of target address
:param tx_params: transaction parameters
"""
(_target, _value) = self.validate_and_normalize_inputs(_target, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_target, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self, _target: str, _value: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_target, _value) = self.validate_and_normalize_inputs(_target, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_target, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _target: str, _value: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_target, _value) = self.validate_and_normalize_inputs(_target, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_target, _value).estimateGas(
tx_params.as_dict()
)
class SymbolMethod(ContractMethod):
"""Various interfaces to the symbol method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TotalSupplyMethod(ContractMethod):
"""Various interfaces to the totalSupply method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Query total supply of token
:param tx_params: transaction parameters
:returns: Total supply of token
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferMethod(ContractMethod):
"""Various interfaces to the transfer method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _to: str, _value: int):
"""Validate the inputs to the transfer method."""
self.validator.assert_valid(
method_name="transfer", parameter_name="_to", argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="transfer",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_to, _value)
def call(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
send `value` token to `to` from `msg.sender`
:param _to: The address of the recipient
:param _value: The amount of token to be transferred
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_to, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
send `value` token to `to` from `msg.sender`
:param _to: The address of the recipient
:param _value: The amount of token to be transferred
:param tx_params: transaction parameters
"""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _to: str, _value: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_to, _value) = self.validate_and_normalize_inputs(_to, _value)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_to, _value).estimateGas(
tx_params.as_dict()
)
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _from: str, _to: str, _value: int):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_to",
argument_value=_to,
)
_to = self.validate_and_checksum_address(_to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="_value",
argument_value=_value,
)
# safeguard against fractional inputs
_value = int(_value)
return (_from, _to, _value)
def call(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> bool:
"""Execute underlying contract method via eth_call.
ERC20 transferFrom, modified such that an allowance of MAX_UINT
represents an unlimited allowance. See
https://github.com/ethereum/EIPs/issues/717
:param _from: Address to transfer from.
:param _to: Address to transfer to.
:param _value: Amount to transfer.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_from, _to, _value).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
ERC20 transferFrom, modified such that an allowance of MAX_UINT
represents an unlimited allowance. See
https://github.com/ethereum/EIPs/issues/717
:param _from: Address to transfer from.
:param _to: Address to transfer to.
:param _value: Amount to transfer.
:param tx_params: transaction parameters
"""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_from: str,
_to: str,
_value: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, _to, _value) = self.validate_and_normalize_inputs(
_from, _to, _value
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, _to, _value).estimateGas(
tx_params.as_dict()
)
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class DummyERC20Token:
"""Wrapper class for DummyERC20Token Solidity contract."""
max_mint_amount: MaxMintAmountMethod
"""Constructor-initialized instance of
:class:`MaxMintAmountMethod`.
"""
allowance: AllowanceMethod
"""Constructor-initialized instance of
:class:`AllowanceMethod`.
"""
approve: ApproveMethod
"""Constructor-initialized instance of
:class:`ApproveMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
decimals: DecimalsMethod
"""Constructor-initialized instance of
:class:`DecimalsMethod`.
"""
mint: MintMethod
"""Constructor-initialized instance of
:class:`MintMethod`.
"""
name: NameMethod
"""Constructor-initialized instance of
:class:`NameMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
set_balance: SetBalanceMethod
"""Constructor-initialized instance of
:class:`SetBalanceMethod`.
"""
symbol: SymbolMethod
"""Constructor-initialized instance of
:class:`SymbolMethod`.
"""
total_supply: TotalSupplyMethod
"""Constructor-initialized instance of
:class:`TotalSupplyMethod`.
"""
transfer: TransferMethod
"""Constructor-initialized instance of
:class:`TransferMethod`.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: DummyERC20TokenValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = DummyERC20TokenValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=DummyERC20Token.abi(),
).functions
self.max_mint_amount = MaxMintAmountMethod(
web3_or_provider, contract_address, functions.MAX_MINT_AMOUNT
)
self.allowance = AllowanceMethod(
web3_or_provider, contract_address, functions.allowance, validator
)
self.approve = ApproveMethod(
web3_or_provider, contract_address, functions.approve, validator
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.decimals = DecimalsMethod(
web3_or_provider, contract_address, functions.decimals
)
self.mint = MintMethod(
web3_or_provider, contract_address, functions.mint, validator
)
self.name = NameMethod(
web3_or_provider, contract_address, functions.name
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.set_balance = SetBalanceMethod(
web3_or_provider, contract_address, functions.setBalance, validator
)
self.symbol = SymbolMethod(
web3_or_provider, contract_address, functions.symbol
)
self.total_supply = TotalSupplyMethod(
web3_or_provider, contract_address, functions.totalSupply
)
self.transfer = TransferMethod(
web3_or_provider, contract_address, functions.transfer, validator
)
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
def get_approval_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Approval event.
:param tx_hash: hash of transaction emitting Approval event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=DummyERC20Token.abi(),
)
.events.Approval()
.processReceipt(tx_receipt)
)
def get_transfer_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Transfer event.
:param tx_hash: hash of transaction emitting Transfer event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=DummyERC20Token.abi(),
)
.events.Transfer()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint256","name":"_decimals","type":"uint256"},{"internalType":"uint256","name":"_totalSupply","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_owner","type":"address"},{"indexed":true,"internalType":"address","name":"_spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_from","type":"address"},{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":false,"internalType":"uint256","name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"constant":true,"inputs":[],"name":"MAX_MINT_AMOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_target","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"setBalance","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/dummy_erc20_token/__init__.py | __init__.py |
"""Generated wrapper for Forwarder Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for Forwarder below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ForwarderValidator,
)
except ImportError:
class ForwarderValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class LibOrderOrder(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerAddress: str
takerAddress: str
feeRecipientAddress: str
senderAddress: str
makerAssetAmount: int
takerAssetAmount: int
makerFee: int
takerFee: int
expirationTimeSeconds: int
salt: int
makerAssetData: Union[bytes, str]
takerAssetData: Union[bytes, str]
makerFeeAssetData: Union[bytes, str]
takerFeeAssetData: Union[bytes, str]
class ApproveMakerAssetProxyMethod(ContractMethod):
"""Various interfaces to the approveMakerAssetProxy method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, asset_data: Union[bytes, str]):
"""Validate the inputs to the approveMakerAssetProxy method."""
self.validator.assert_valid(
method_name="approveMakerAssetProxy",
parameter_name="assetData",
argument_value=asset_data,
)
return asset_data
def call(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Approves the respective proxy for a given asset to transfer tokens on
the Forwarder contract's behalf. This is necessary because an order fee
denominated in the maker asset (i.e. a percentage fee) is sent by the
Forwarder contract to the fee recipient. This method needs to be called
before forwarding orders of a maker asset that hasn't previously been
approved.
:param assetData: Byte array encoded for the respective asset proxy.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_data).call(tx_params.as_dict())
def send_transaction(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Approves the respective proxy for a given asset to transfer tokens on
the Forwarder contract's behalf. This is necessary because an order fee
denominated in the maker asset (i.e. a percentage fee) is sent by the
Forwarder contract to the fee recipient. This method needs to be called
before forwarding orders of a maker asset that hasn't previously been
approved.
:param assetData: Byte array encoded for the respective asset proxy.
:param tx_params: transaction parameters
"""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).transact(
tx_params.as_dict()
)
def build_transaction(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data) = self.validate_and_normalize_inputs(asset_data)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data).estimateGas(
tx_params.as_dict()
)
class MarketBuyOrdersWithEthMethod(ContractMethod):
"""Various interfaces to the marketBuyOrdersWithEth method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
maker_asset_buy_amount: int,
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
):
"""Validate the inputs to the marketBuyOrdersWithEth method."""
self.validator.assert_valid(
method_name="marketBuyOrdersWithEth",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="marketBuyOrdersWithEth",
parameter_name="makerAssetBuyAmount",
argument_value=maker_asset_buy_amount,
)
# safeguard against fractional inputs
maker_asset_buy_amount = int(maker_asset_buy_amount)
self.validator.assert_valid(
method_name="marketBuyOrdersWithEth",
parameter_name="signatures",
argument_value=signatures,
)
self.validator.assert_valid(
method_name="marketBuyOrdersWithEth",
parameter_name="feePercentage",
argument_value=fee_percentage,
)
# safeguard against fractional inputs
fee_percentage = int(fee_percentage)
self.validator.assert_valid(
method_name="marketBuyOrdersWithEth",
parameter_name="feeRecipient",
argument_value=fee_recipient,
)
fee_recipient = self.validate_and_checksum_address(fee_recipient)
return (
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
)
def call(
self,
orders: List[LibOrderOrder],
maker_asset_buy_amount: int,
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
tx_params: Optional[TxParams] = None,
) -> Tuple[int, int, int]:
"""Execute underlying contract method via eth_call.
Attempt to buy makerAssetBuyAmount of makerAsset by selling ETH
provided with transaction. The Forwarder may *fill* more than
makerAssetBuyAmount of the makerAsset so that it can pay takerFees
where takerFeeAssetData == makerAssetData (i.e. percentage fees). Any
ETH not spent will be refunded to sender.
:param feePercentage: Percentage of WETH sold that will payed as fee to
forwarding contract feeRecipient.
:param feeRecipient: Address that will receive ETH when orders are
filled.
:param makerAssetBuyAmount: Desired amount of makerAsset to purchase.
:param orders: Array of order specifications used containing desired
makerAsset and WETH as takerAsset.
:param signatures: Proofs that orders have been created by makers.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
) = self.validate_and_normalize_inputs(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
)
def send_transaction(
self,
orders: List[LibOrderOrder],
maker_asset_buy_amount: int,
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Attempt to buy makerAssetBuyAmount of makerAsset by selling ETH
provided with transaction. The Forwarder may *fill* more than
makerAssetBuyAmount of the makerAsset so that it can pay takerFees
where takerFeeAssetData == makerAssetData (i.e. percentage fees). Any
ETH not spent will be refunded to sender.
:param feePercentage: Percentage of WETH sold that will payed as fee to
forwarding contract feeRecipient.
:param feeRecipient: Address that will receive ETH when orders are
filled.
:param makerAssetBuyAmount: Desired amount of makerAsset to purchase.
:param orders: Array of order specifications used containing desired
makerAsset and WETH as takerAsset.
:param signatures: Proofs that orders have been created by makers.
:param tx_params: transaction parameters
"""
(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
) = self.validate_and_normalize_inputs(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
maker_asset_buy_amount: int,
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
) = self.validate_and_normalize_inputs(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
maker_asset_buy_amount: int,
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
) = self.validate_and_normalize_inputs(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders,
maker_asset_buy_amount,
signatures,
fee_percentage,
fee_recipient,
).estimateGas(tx_params.as_dict())
class MarketSellOrdersWithEthMethod(ContractMethod):
"""Various interfaces to the marketSellOrdersWithEth method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
orders: List[LibOrderOrder],
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
):
"""Validate the inputs to the marketSellOrdersWithEth method."""
self.validator.assert_valid(
method_name="marketSellOrdersWithEth",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="marketSellOrdersWithEth",
parameter_name="signatures",
argument_value=signatures,
)
self.validator.assert_valid(
method_name="marketSellOrdersWithEth",
parameter_name="feePercentage",
argument_value=fee_percentage,
)
# safeguard against fractional inputs
fee_percentage = int(fee_percentage)
self.validator.assert_valid(
method_name="marketSellOrdersWithEth",
parameter_name="feeRecipient",
argument_value=fee_recipient,
)
fee_recipient = self.validate_and_checksum_address(fee_recipient)
return (orders, signatures, fee_percentage, fee_recipient)
def call(
self,
orders: List[LibOrderOrder],
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
tx_params: Optional[TxParams] = None,
) -> Tuple[int, int, int]:
"""Execute underlying contract method via eth_call.
Purchases as much of orders' makerAssets as possible by selling as much
of the ETH value sent as possible, accounting for order and forwarder
fees.
:param feePercentage: Percentage of WETH sold that will payed as fee to
forwarding contract feeRecipient.
:param feeRecipient: Address that will receive ETH when orders are
filled.
:param orders: Array of order specifications used containing desired
makerAsset and WETH as takerAsset.
:param signatures: Proofs that orders have been created by makers.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
orders,
signatures,
fee_percentage,
fee_recipient,
) = self.validate_and_normalize_inputs(
orders, signatures, fee_percentage, fee_recipient
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
orders, signatures, fee_percentage, fee_recipient
).call(tx_params.as_dict())
return (
returned[0],
returned[1],
returned[2],
)
def send_transaction(
self,
orders: List[LibOrderOrder],
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Purchases as much of orders' makerAssets as possible by selling as much
of the ETH value sent as possible, accounting for order and forwarder
fees.
:param feePercentage: Percentage of WETH sold that will payed as fee to
forwarding contract feeRecipient.
:param feeRecipient: Address that will receive ETH when orders are
filled.
:param orders: Array of order specifications used containing desired
makerAsset and WETH as takerAsset.
:param signatures: Proofs that orders have been created by makers.
:param tx_params: transaction parameters
"""
(
orders,
signatures,
fee_percentage,
fee_recipient,
) = self.validate_and_normalize_inputs(
orders, signatures, fee_percentage, fee_recipient
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, signatures, fee_percentage, fee_recipient
).transact(tx_params.as_dict())
def build_transaction(
self,
orders: List[LibOrderOrder],
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
orders,
signatures,
fee_percentage,
fee_recipient,
) = self.validate_and_normalize_inputs(
orders, signatures, fee_percentage, fee_recipient
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, signatures, fee_percentage, fee_recipient
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
orders: List[LibOrderOrder],
signatures: List[Union[bytes, str]],
fee_percentage: int,
fee_recipient: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
orders,
signatures,
fee_percentage,
fee_recipient,
) = self.validate_and_normalize_inputs(
orders, signatures, fee_percentage, fee_recipient
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
orders, signatures, fee_percentage, fee_recipient
).estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
class WithdrawAssetMethod(ContractMethod):
"""Various interfaces to the withdrawAsset method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, asset_data: Union[bytes, str], amount: int
):
"""Validate the inputs to the withdrawAsset method."""
self.validator.assert_valid(
method_name="withdrawAsset",
parameter_name="assetData",
argument_value=asset_data,
)
self.validator.assert_valid(
method_name="withdrawAsset",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return (asset_data, amount)
def call(
self,
asset_data: Union[bytes, str],
amount: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Withdraws assets from this contract. It may be used by the owner to
withdraw assets that were accidentally sent to this contract.
:param amount: Amount of the asset to withdraw.
:param assetData: Byte array encoded for the respective asset proxy.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(asset_data, amount) = self.validate_and_normalize_inputs(
asset_data, amount
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_data, amount).call(tx_params.as_dict())
def send_transaction(
self,
asset_data: Union[bytes, str],
amount: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Withdraws assets from this contract. It may be used by the owner to
withdraw assets that were accidentally sent to this contract.
:param amount: Amount of the asset to withdraw.
:param assetData: Byte array encoded for the respective asset proxy.
:param tx_params: transaction parameters
"""
(asset_data, amount) = self.validate_and_normalize_inputs(
asset_data, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data, amount).transact(
tx_params.as_dict()
)
def build_transaction(
self,
asset_data: Union[bytes, str],
amount: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(asset_data, amount) = self.validate_and_normalize_inputs(
asset_data, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data, amount).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
asset_data: Union[bytes, str],
amount: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data, amount) = self.validate_and_normalize_inputs(
asset_data, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data, amount).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class Forwarder:
"""Wrapper class for Forwarder Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
approve_maker_asset_proxy: ApproveMakerAssetProxyMethod
"""Constructor-initialized instance of
:class:`ApproveMakerAssetProxyMethod`.
"""
market_buy_orders_with_eth: MarketBuyOrdersWithEthMethod
"""Constructor-initialized instance of
:class:`MarketBuyOrdersWithEthMethod`.
"""
market_sell_orders_with_eth: MarketSellOrdersWithEthMethod
"""Constructor-initialized instance of
:class:`MarketSellOrdersWithEthMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
withdraw_asset: WithdrawAssetMethod
"""Constructor-initialized instance of
:class:`WithdrawAssetMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ForwarderValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ForwarderValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=Forwarder.abi()
).functions
self.approve_maker_asset_proxy = ApproveMakerAssetProxyMethod(
web3_or_provider,
contract_address,
functions.approveMakerAssetProxy,
validator,
)
self.market_buy_orders_with_eth = MarketBuyOrdersWithEthMethod(
web3_or_provider,
contract_address,
functions.marketBuyOrdersWithEth,
validator,
)
self.market_sell_orders_with_eth = MarketSellOrdersWithEthMethod(
web3_or_provider,
contract_address,
functions.marketSellOrdersWithEth,
validator,
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
self.withdraw_asset = WithdrawAssetMethod(
web3_or_provider,
contract_address,
functions.withdrawAsset,
validator,
)
def get_ownership_transferred_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for OwnershipTransferred event.
:param tx_hash: hash of transaction emitting OwnershipTransferred event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=Forwarder.abi(),
)
.events.OwnershipTransferred()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"address","name":"_exchange","type":"address"},{"internalType":"address","name":"_weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":false,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"}],"name":"approveMakerAssetProxy","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"uint256","name":"makerAssetBuyAmount","type":"uint256"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"},{"internalType":"uint256","name":"feePercentage","type":"uint256"},{"internalType":"address payable","name":"feeRecipient","type":"address"}],"name":"marketBuyOrdersWithEth","outputs":[{"internalType":"uint256","name":"wethSpentAmount","type":"uint256"},{"internalType":"uint256","name":"makerAssetAcquiredAmount","type":"uint256"},{"internalType":"uint256","name":"ethFeePaid","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"address","name":"takerAddress","type":"address"},{"internalType":"address","name":"feeRecipientAddress","type":"address"},{"internalType":"address","name":"senderAddress","type":"address"},{"internalType":"uint256","name":"makerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"takerAssetAmount","type":"uint256"},{"internalType":"uint256","name":"makerFee","type":"uint256"},{"internalType":"uint256","name":"takerFee","type":"uint256"},{"internalType":"uint256","name":"expirationTimeSeconds","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"bytes","name":"makerAssetData","type":"bytes"},{"internalType":"bytes","name":"takerAssetData","type":"bytes"},{"internalType":"bytes","name":"makerFeeAssetData","type":"bytes"},{"internalType":"bytes","name":"takerFeeAssetData","type":"bytes"}],"internalType":"struct LibOrder.Order[]","name":"orders","type":"tuple[]"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"},{"internalType":"uint256","name":"feePercentage","type":"uint256"},{"internalType":"address payable","name":"feeRecipient","type":"address"}],"name":"marketSellOrdersWithEth","outputs":[{"internalType":"uint256","name":"wethSpentAmount","type":"uint256"},{"internalType":"uint256","name":"makerAssetAcquiredAmount","type":"uint256"},{"internalType":"uint256","name":"ethFeePaid","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawAsset","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/forwarder/__init__.py | __init__.py |
"""Generated wrapper for OrderValidator Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for OrderValidator below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
OrderValidatorValidator,
)
except ImportError:
class OrderValidatorValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class Tuple0x260219a2(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerAddress: str
takerAddress: str
feeRecipientAddress: str
senderAddress: str
makerAssetAmount: int
takerAssetAmount: int
makerFee: int
takerFee: int
expirationTimeSeconds: int
salt: int
makerAssetData: Union[bytes, str]
takerAssetData: Union[bytes, str]
class Tuple0xb1e4a1ae(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
orderStatus: int
orderHash: Union[bytes, str]
orderTakerAssetFilledAmount: int
class Tuple0x8cfc0927(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerBalance: int
makerAllowance: int
takerBalance: int
takerAllowance: int
makerZrxBalance: int
makerZrxAllowance: int
takerZrxBalance: int
takerZrxAllowance: int
class GetOrderAndTraderInfoMethod(ContractMethod):
"""Various interfaces to the getOrderAndTraderInfo method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, order: Tuple0x260219a2, taker_address: str
):
"""Validate the inputs to the getOrderAndTraderInfo method."""
self.validator.assert_valid(
method_name="getOrderAndTraderInfo",
parameter_name="order",
argument_value=order,
)
self.validator.assert_valid(
method_name="getOrderAndTraderInfo",
parameter_name="takerAddress",
argument_value=taker_address,
)
taker_address = self.validate_and_checksum_address(taker_address)
return (order, taker_address)
def call(
self,
order: Tuple0x260219a2,
taker_address: str,
tx_params: Optional[TxParams] = None,
) -> Tuple[Tuple0xb1e4a1ae, Tuple0x8cfc0927]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(order, taker_address) = self.validate_and_normalize_inputs(
order, taker_address
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(order, taker_address).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
)
def estimate_gas(
self,
order: Tuple0x260219a2,
taker_address: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(order, taker_address) = self.validate_and_normalize_inputs(
order, taker_address
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order, taker_address).estimateGas(
tx_params.as_dict()
)
class GetBalanceAndAllowanceMethod(ContractMethod):
"""Various interfaces to the getBalanceAndAllowance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, target: str, asset_data: Union[bytes, str]
):
"""Validate the inputs to the getBalanceAndAllowance method."""
self.validator.assert_valid(
method_name="getBalanceAndAllowance",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="getBalanceAndAllowance",
parameter_name="assetData",
argument_value=asset_data,
)
return (target, asset_data)
def call(
self,
target: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple[int, int]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(target, asset_data) = self.validate_and_normalize_inputs(
target, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(target, asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
)
def estimate_gas(
self,
target: str,
asset_data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(target, asset_data) = self.validate_and_normalize_inputs(
target, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, asset_data).estimateGas(
tx_params.as_dict()
)
class GetOrdersAndTradersInfoMethod(ContractMethod):
"""Various interfaces to the getOrdersAndTradersInfo method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, orders: List[Tuple0x260219a2], taker_addresses: List[str]
):
"""Validate the inputs to the getOrdersAndTradersInfo method."""
self.validator.assert_valid(
method_name="getOrdersAndTradersInfo",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="getOrdersAndTradersInfo",
parameter_name="takerAddresses",
argument_value=taker_addresses,
)
return (orders, taker_addresses)
def call(
self,
orders: List[Tuple0x260219a2],
taker_addresses: List[str],
tx_params: Optional[TxParams] = None,
) -> Tuple[List[Tuple0xb1e4a1ae], List[Tuple0x8cfc0927]]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(orders, taker_addresses) = self.validate_and_normalize_inputs(
orders, taker_addresses
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(orders, taker_addresses).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
)
def estimate_gas(
self,
orders: List[Tuple0x260219a2],
taker_addresses: List[str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(orders, taker_addresses) = self.validate_and_normalize_inputs(
orders, taker_addresses
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(orders, taker_addresses).estimateGas(
tx_params.as_dict()
)
class GetTradersInfoMethod(ContractMethod):
"""Various interfaces to the getTradersInfo method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, orders: List[Tuple0x260219a2], taker_addresses: List[str]
):
"""Validate the inputs to the getTradersInfo method."""
self.validator.assert_valid(
method_name="getTradersInfo",
parameter_name="orders",
argument_value=orders,
)
self.validator.assert_valid(
method_name="getTradersInfo",
parameter_name="takerAddresses",
argument_value=taker_addresses,
)
return (orders, taker_addresses)
def call(
self,
orders: List[Tuple0x260219a2],
taker_addresses: List[str],
tx_params: Optional[TxParams] = None,
) -> List[Tuple0x8cfc0927]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(orders, taker_addresses) = self.validate_and_normalize_inputs(
orders, taker_addresses
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(orders, taker_addresses).call(
tx_params.as_dict()
)
return [
Tuple0x8cfc0927(
makerBalance=element[0],
makerAllowance=element[1],
takerBalance=element[2],
takerAllowance=element[3],
makerZrxBalance=element[4],
makerZrxAllowance=element[5],
takerZrxBalance=element[6],
takerZrxAllowance=element[7],
)
for element in returned
]
def estimate_gas(
self,
orders: List[Tuple0x260219a2],
taker_addresses: List[str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(orders, taker_addresses) = self.validate_and_normalize_inputs(
orders, taker_addresses
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(orders, taker_addresses).estimateGas(
tx_params.as_dict()
)
class GetErc721TokenOwnerMethod(ContractMethod):
"""Various interfaces to the getERC721TokenOwner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, token: str, token_id: int):
"""Validate the inputs to the getERC721TokenOwner method."""
self.validator.assert_valid(
method_name="getERC721TokenOwner",
parameter_name="token",
argument_value=token,
)
token = self.validate_and_checksum_address(token)
self.validator.assert_valid(
method_name="getERC721TokenOwner",
parameter_name="tokenId",
argument_value=token_id,
)
# safeguard against fractional inputs
token_id = int(token_id)
return (token, token_id)
def call(
self, token: str, token_id: int, tx_params: Optional[TxParams] = None
) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(token, token_id) = self.validate_and_normalize_inputs(token, token_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(token, token_id).call(
tx_params.as_dict()
)
return str(returned)
def estimate_gas(
self, token: str, token_id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(token, token_id) = self.validate_and_normalize_inputs(token, token_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(token, token_id).estimateGas(
tx_params.as_dict()
)
class GetBalancesAndAllowancesMethod(ContractMethod):
"""Various interfaces to the getBalancesAndAllowances method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, target: str, asset_data: List[Union[bytes, str]]
):
"""Validate the inputs to the getBalancesAndAllowances method."""
self.validator.assert_valid(
method_name="getBalancesAndAllowances",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="getBalancesAndAllowances",
parameter_name="assetData",
argument_value=asset_data,
)
return (target, asset_data)
def call(
self,
target: str,
asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> Tuple[List[int], List[int]]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(target, asset_data) = self.validate_and_normalize_inputs(
target, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(target, asset_data).call(
tx_params.as_dict()
)
return (
returned[0],
returned[1],
)
def estimate_gas(
self,
target: str,
asset_data: List[Union[bytes, str]],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(target, asset_data) = self.validate_and_normalize_inputs(
target, asset_data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, asset_data).estimateGas(
tx_params.as_dict()
)
class GetTraderInfoMethod(ContractMethod):
"""Various interfaces to the getTraderInfo method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, order: Tuple0x260219a2, taker_address: str
):
"""Validate the inputs to the getTraderInfo method."""
self.validator.assert_valid(
method_name="getTraderInfo",
parameter_name="order",
argument_value=order,
)
self.validator.assert_valid(
method_name="getTraderInfo",
parameter_name="takerAddress",
argument_value=taker_address,
)
taker_address = self.validate_and_checksum_address(taker_address)
return (order, taker_address)
def call(
self,
order: Tuple0x260219a2,
taker_address: str,
tx_params: Optional[TxParams] = None,
) -> Tuple0x8cfc0927:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(order, taker_address) = self.validate_and_normalize_inputs(
order, taker_address
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(order, taker_address).call(
tx_params.as_dict()
)
return Tuple0x8cfc0927(
makerBalance=returned[0],
makerAllowance=returned[1],
takerBalance=returned[2],
takerAllowance=returned[3],
makerZrxBalance=returned[4],
makerZrxAllowance=returned[5],
takerZrxBalance=returned[6],
takerZrxAllowance=returned[7],
)
def estimate_gas(
self,
order: Tuple0x260219a2,
taker_address: str,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(order, taker_address) = self.validate_and_normalize_inputs(
order, taker_address
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order, taker_address).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class OrderValidator:
"""Wrapper class for OrderValidator Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
get_order_and_trader_info: GetOrderAndTraderInfoMethod
"""Constructor-initialized instance of
:class:`GetOrderAndTraderInfoMethod`.
"""
get_balance_and_allowance: GetBalanceAndAllowanceMethod
"""Constructor-initialized instance of
:class:`GetBalanceAndAllowanceMethod`.
"""
get_orders_and_traders_info: GetOrdersAndTradersInfoMethod
"""Constructor-initialized instance of
:class:`GetOrdersAndTradersInfoMethod`.
"""
get_traders_info: GetTradersInfoMethod
"""Constructor-initialized instance of
:class:`GetTradersInfoMethod`.
"""
get_erc721_token_owner: GetErc721TokenOwnerMethod
"""Constructor-initialized instance of
:class:`GetErc721TokenOwnerMethod`.
"""
get_balances_and_allowances: GetBalancesAndAllowancesMethod
"""Constructor-initialized instance of
:class:`GetBalancesAndAllowancesMethod`.
"""
get_trader_info: GetTraderInfoMethod
"""Constructor-initialized instance of
:class:`GetTraderInfoMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: OrderValidatorValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = OrderValidatorValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=OrderValidator.abi(),
).functions
self.get_order_and_trader_info = GetOrderAndTraderInfoMethod(
web3_or_provider,
contract_address,
functions.getOrderAndTraderInfo,
validator,
)
self.get_balance_and_allowance = GetBalanceAndAllowanceMethod(
web3_or_provider,
contract_address,
functions.getBalanceAndAllowance,
validator,
)
self.get_orders_and_traders_info = GetOrdersAndTradersInfoMethod(
web3_or_provider,
contract_address,
functions.getOrdersAndTradersInfo,
validator,
)
self.get_traders_info = GetTradersInfoMethod(
web3_or_provider,
contract_address,
functions.getTradersInfo,
validator,
)
self.get_erc721_token_owner = GetErc721TokenOwnerMethod(
web3_or_provider,
contract_address,
functions.getERC721TokenOwner,
validator,
)
self.get_balances_and_allowances = GetBalancesAndAllowancesMethod(
web3_or_provider,
contract_address,
functions.getBalancesAndAllowances,
validator,
)
self.get_trader_info = GetTraderInfoMethod(
web3_or_provider,
contract_address,
functions.getTraderInfo,
validator,
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":true,"inputs":[{"components":[{"name":"makerAddress","type":"address"},{"name":"takerAddress","type":"address"},{"name":"feeRecipientAddress","type":"address"},{"name":"senderAddress","type":"address"},{"name":"makerAssetAmount","type":"uint256"},{"name":"takerAssetAmount","type":"uint256"},{"name":"makerFee","type":"uint256"},{"name":"takerFee","type":"uint256"},{"name":"expirationTimeSeconds","type":"uint256"},{"name":"salt","type":"uint256"},{"name":"makerAssetData","type":"bytes"},{"name":"takerAssetData","type":"bytes"}],"name":"order","type":"tuple"},{"name":"takerAddress","type":"address"}],"name":"getOrderAndTraderInfo","outputs":[{"components":[{"name":"orderStatus","type":"uint8"},{"name":"orderHash","type":"bytes32"},{"name":"orderTakerAssetFilledAmount","type":"uint256"}],"name":"orderInfo","type":"tuple"},{"components":[{"name":"makerBalance","type":"uint256"},{"name":"makerAllowance","type":"uint256"},{"name":"takerBalance","type":"uint256"},{"name":"takerAllowance","type":"uint256"},{"name":"makerZrxBalance","type":"uint256"},{"name":"makerZrxAllowance","type":"uint256"},{"name":"takerZrxBalance","type":"uint256"},{"name":"takerZrxAllowance","type":"uint256"}],"name":"traderInfo","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"target","type":"address"},{"name":"assetData","type":"bytes"}],"name":"getBalanceAndAllowance","outputs":[{"name":"balance","type":"uint256"},{"name":"allowance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"name":"makerAddress","type":"address"},{"name":"takerAddress","type":"address"},{"name":"feeRecipientAddress","type":"address"},{"name":"senderAddress","type":"address"},{"name":"makerAssetAmount","type":"uint256"},{"name":"takerAssetAmount","type":"uint256"},{"name":"makerFee","type":"uint256"},{"name":"takerFee","type":"uint256"},{"name":"expirationTimeSeconds","type":"uint256"},{"name":"salt","type":"uint256"},{"name":"makerAssetData","type":"bytes"},{"name":"takerAssetData","type":"bytes"}],"name":"orders","type":"tuple[]"},{"name":"takerAddresses","type":"address[]"}],"name":"getOrdersAndTradersInfo","outputs":[{"components":[{"name":"orderStatus","type":"uint8"},{"name":"orderHash","type":"bytes32"},{"name":"orderTakerAssetFilledAmount","type":"uint256"}],"name":"ordersInfo","type":"tuple[]"},{"components":[{"name":"makerBalance","type":"uint256"},{"name":"makerAllowance","type":"uint256"},{"name":"takerBalance","type":"uint256"},{"name":"takerAllowance","type":"uint256"},{"name":"makerZrxBalance","type":"uint256"},{"name":"makerZrxAllowance","type":"uint256"},{"name":"takerZrxBalance","type":"uint256"},{"name":"takerZrxAllowance","type":"uint256"}],"name":"tradersInfo","type":"tuple[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"name":"makerAddress","type":"address"},{"name":"takerAddress","type":"address"},{"name":"feeRecipientAddress","type":"address"},{"name":"senderAddress","type":"address"},{"name":"makerAssetAmount","type":"uint256"},{"name":"takerAssetAmount","type":"uint256"},{"name":"makerFee","type":"uint256"},{"name":"takerFee","type":"uint256"},{"name":"expirationTimeSeconds","type":"uint256"},{"name":"salt","type":"uint256"},{"name":"makerAssetData","type":"bytes"},{"name":"takerAssetData","type":"bytes"}],"name":"orders","type":"tuple[]"},{"name":"takerAddresses","type":"address[]"}],"name":"getTradersInfo","outputs":[{"components":[{"name":"makerBalance","type":"uint256"},{"name":"makerAllowance","type":"uint256"},{"name":"takerBalance","type":"uint256"},{"name":"takerAllowance","type":"uint256"},{"name":"makerZrxBalance","type":"uint256"},{"name":"makerZrxAllowance","type":"uint256"},{"name":"takerZrxBalance","type":"uint256"},{"name":"takerZrxAllowance","type":"uint256"}],"name":"","type":"tuple[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"token","type":"address"},{"name":"tokenId","type":"uint256"}],"name":"getERC721TokenOwner","outputs":[{"name":"owner","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"target","type":"address"},{"name":"assetData","type":"bytes[]"}],"name":"getBalancesAndAllowances","outputs":[{"name":"","type":"uint256[]"},{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"components":[{"name":"makerAddress","type":"address"},{"name":"takerAddress","type":"address"},{"name":"feeRecipientAddress","type":"address"},{"name":"senderAddress","type":"address"},{"name":"makerAssetAmount","type":"uint256"},{"name":"takerAssetAmount","type":"uint256"},{"name":"makerFee","type":"uint256"},{"name":"takerFee","type":"uint256"},{"name":"expirationTimeSeconds","type":"uint256"},{"name":"salt","type":"uint256"},{"name":"makerAssetData","type":"bytes"},{"name":"takerAssetData","type":"bytes"}],"name":"order","type":"tuple"},{"name":"takerAddress","type":"address"}],"name":"getTraderInfo","outputs":[{"components":[{"name":"makerBalance","type":"uint256"},{"name":"makerAllowance","type":"uint256"},{"name":"takerBalance","type":"uint256"},{"name":"takerAllowance","type":"uint256"},{"name":"makerZrxBalance","type":"uint256"},{"name":"makerZrxAllowance","type":"uint256"},{"name":"takerZrxBalance","type":"uint256"},{"name":"takerZrxAllowance","type":"uint256"}],"name":"traderInfo","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_exchange","type":"address"},{"name":"_zrxAssetData","type":"bytes"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/order_validator/__init__.py | __init__.py |
"""Generated wrapper for IAssetProxy Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for IAssetProxy below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
IAssetProxyValidator,
)
except ImportError:
class IAssetProxyValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, asset_data: Union[bytes, str], _from: str, to: str, amount: int
):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="assetData",
argument_value=asset_data,
)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="transferFrom", parameter_name="to", argument_value=to,
)
to = self.validate_and_checksum_address(to)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return (asset_data, _from, to, amount)
def call(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
Transfers assets. Either succeeds or throws.
:param amount: Amount of asset to transfer.
:param assetData: Byte array encoded for the respective asset proxy.
:param from: Address to transfer asset from.
:param to: Address to transfer asset to.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(asset_data, _from, to, amount).call(
tx_params.as_dict()
)
def send_transaction(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Transfers assets. Either succeeds or throws.
:param amount: Amount of asset to transfer.
:param assetData: Byte array encoded for the respective asset proxy.
:param from: Address to transfer asset from.
:param to: Address to transfer asset to.
:param tx_params: transaction parameters
"""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(asset_data, _from, to, amount).transact(
tx_params.as_dict()
)
def build_transaction(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, _from, to, amount
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
asset_data: Union[bytes, str],
_from: str,
to: str,
amount: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(asset_data, _from, to, amount) = self.validate_and_normalize_inputs(
asset_data, _from, to, amount
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
asset_data, _from, to, amount
).estimateGas(tx_params.as_dict())
class GetProxyIdMethod(ContractMethod):
"""Various interfaces to the getProxyId method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Gets the proxy id associated with the proxy address.
:param tx_params: transaction parameters
:returns: Proxy id.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class IAssetProxy:
"""Wrapper class for IAssetProxy Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
get_proxy_id: GetProxyIdMethod
"""Constructor-initialized instance of
:class:`GetProxyIdMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: IAssetProxyValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = IAssetProxyValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=IAssetProxy.abi(),
).functions
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.get_proxy_id = GetProxyIdMethod(
web3_or_provider, contract_address, functions.getProxyId
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":false,"inputs":[{"internalType":"bytes","name":"assetData","type":"bytes"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getProxyId","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"pure","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/i_asset_proxy/__init__.py | __init__.py |
"""Generated wrapper for DutchAuction Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for DutchAuction below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
DutchAuctionValidator,
)
except ImportError:
class DutchAuctionValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class Tuple0xbb41e5b3(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerAssetFilledAmount: int
takerAssetFilledAmount: int
makerFeePaid: int
takerFeePaid: int
class Tuple0x054ca44e(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
left: Tuple0xbb41e5b3
right: Tuple0xbb41e5b3
leftMakerAssetSpreadAmount: int
class Tuple0x260219a2(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
makerAddress: str
takerAddress: str
feeRecipientAddress: str
senderAddress: str
makerAssetAmount: int
takerAssetAmount: int
makerFee: int
takerFee: int
expirationTimeSeconds: int
salt: int
makerAssetData: Union[bytes, str]
takerAssetData: Union[bytes, str]
class Tuple0xdc58a88c(TypedDict):
"""Python representation of a tuple or struct.
Solidity compiler output does not include the names of structs that appear
in method definitions. A tuple found in an ABI may have been written in
Solidity as a literal, anonymous tuple, or it may have been written as a
named `struct`:code:, but there is no way to tell from the compiler
output. This class represents a tuple that appeared in a method
definition. Its name is derived from a hash of that tuple's field names,
and every method whose ABI refers to a tuple with that same list of field
names will have a generated wrapper method that refers to this class.
Any members of type `bytes`:code: should be encoded as UTF-8, which can be
accomplished via `str.encode("utf_8")`:code:
"""
beginTimeSeconds: int
endTimeSeconds: int
beginAmount: int
endAmount: int
currentAmount: int
currentTimeSeconds: int
class GetAuctionDetailsMethod(ContractMethod):
"""Various interfaces to the getAuctionDetails method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, order: Tuple0x260219a2):
"""Validate the inputs to the getAuctionDetails method."""
self.validator.assert_valid(
method_name="getAuctionDetails",
parameter_name="order",
argument_value=order,
)
return order
def call(
self, order: Tuple0x260219a2, tx_params: Optional[TxParams] = None
) -> Tuple0xdc58a88c:
"""Execute underlying contract method via eth_call.
Calculates the Auction Details for the given order
:param order: The sell order
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(order).call(tx_params.as_dict())
return Tuple0xdc58a88c(
beginTimeSeconds=returned[0],
endTimeSeconds=returned[1],
beginAmount=returned[2],
endAmount=returned[3],
currentAmount=returned[4],
currentTimeSeconds=returned[5],
)
def send_transaction(
self, order: Tuple0x260219a2, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Calculates the Auction Details for the given order
:param order: The sell order
:param tx_params: transaction parameters
"""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order).transact(tx_params.as_dict())
def build_transaction(
self, order: Tuple0x260219a2, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, order: Tuple0x260219a2, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(order) = self.validate_and_normalize_inputs(order)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(order).estimateGas(tx_params.as_dict())
class MatchOrdersMethod(ContractMethod):
"""Various interfaces to the matchOrders method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
buy_order: Tuple0x260219a2,
sell_order: Tuple0x260219a2,
buy_signature: Union[bytes, str],
sell_signature: Union[bytes, str],
):
"""Validate the inputs to the matchOrders method."""
self.validator.assert_valid(
method_name="matchOrders",
parameter_name="buyOrder",
argument_value=buy_order,
)
self.validator.assert_valid(
method_name="matchOrders",
parameter_name="sellOrder",
argument_value=sell_order,
)
self.validator.assert_valid(
method_name="matchOrders",
parameter_name="buySignature",
argument_value=buy_signature,
)
self.validator.assert_valid(
method_name="matchOrders",
parameter_name="sellSignature",
argument_value=sell_signature,
)
return (buy_order, sell_order, buy_signature, sell_signature)
def call(
self,
buy_order: Tuple0x260219a2,
sell_order: Tuple0x260219a2,
buy_signature: Union[bytes, str],
sell_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Tuple0x054ca44e:
"""Execute underlying contract method via eth_call.
Matches the buy and sell orders at an amount given the following: the
current block time, the auction start time and the auction begin
amount. The sell order is a an order at the lowest amount at the end of
the auction. Excess from the match is transferred to the seller. Over
time the price moves from beginAmount to endAmount given the current
block.timestamp. sellOrder.expiryTimeSeconds is the end time of the
auction. sellOrder.takerAssetAmount is the end amount of the auction
(lowest possible amount). sellOrder.makerAssetData is the ABI encoded
Asset Proxy data with the following data appended
buyOrder.makerAssetData is the buyers bid on the auction, must meet the
amount for the current block timestamp (uint256 beginTimeSeconds,
uint256 beginAmount). This function reverts in the following scenarios:
* Auction has not started (auctionDetails.currentTimeSeconds <
auctionDetails.beginTimeSeconds) * Auction has expired
(auctionDetails.endTimeSeconds < auctionDetails.currentTimeSeconds) *
Amount is invalid: Buy order amount is too low
(buyOrder.makerAssetAmount < auctionDetails.currentAmount) * Amount is
invalid: Invalid begin amount (auctionDetails.beginAmount >
auctionDetails.endAmount) * Any failure in the 0x Match Orders
:param buyOrder: The Buyer's order. This order is for the current
expected price of the auction.
:param buySignature: Proof that order was created by the buyer.
:param sellOrder: The Seller's order. This order is for the lowest
amount (at the end of the auction).
:param sellSignature: Proof that order was created by the seller.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(
buy_order,
sell_order,
buy_signature,
sell_signature,
) = self.validate_and_normalize_inputs(
buy_order, sell_order, buy_signature, sell_signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(
buy_order, sell_order, buy_signature, sell_signature
).call(tx_params.as_dict())
return Tuple0x054ca44e(
left=returned[0],
right=returned[1],
leftMakerAssetSpreadAmount=returned[2],
)
def send_transaction(
self,
buy_order: Tuple0x260219a2,
sell_order: Tuple0x260219a2,
buy_signature: Union[bytes, str],
sell_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Matches the buy and sell orders at an amount given the following: the
current block time, the auction start time and the auction begin
amount. The sell order is a an order at the lowest amount at the end of
the auction. Excess from the match is transferred to the seller. Over
time the price moves from beginAmount to endAmount given the current
block.timestamp. sellOrder.expiryTimeSeconds is the end time of the
auction. sellOrder.takerAssetAmount is the end amount of the auction
(lowest possible amount). sellOrder.makerAssetData is the ABI encoded
Asset Proxy data with the following data appended
buyOrder.makerAssetData is the buyers bid on the auction, must meet the
amount for the current block timestamp (uint256 beginTimeSeconds,
uint256 beginAmount). This function reverts in the following scenarios:
* Auction has not started (auctionDetails.currentTimeSeconds <
auctionDetails.beginTimeSeconds) * Auction has expired
(auctionDetails.endTimeSeconds < auctionDetails.currentTimeSeconds) *
Amount is invalid: Buy order amount is too low
(buyOrder.makerAssetAmount < auctionDetails.currentAmount) * Amount is
invalid: Invalid begin amount (auctionDetails.beginAmount >
auctionDetails.endAmount) * Any failure in the 0x Match Orders
:param buyOrder: The Buyer's order. This order is for the current
expected price of the auction.
:param buySignature: Proof that order was created by the buyer.
:param sellOrder: The Seller's order. This order is for the lowest
amount (at the end of the auction).
:param sellSignature: Proof that order was created by the seller.
:param tx_params: transaction parameters
"""
(
buy_order,
sell_order,
buy_signature,
sell_signature,
) = self.validate_and_normalize_inputs(
buy_order, sell_order, buy_signature, sell_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
buy_order, sell_order, buy_signature, sell_signature
).transact(tx_params.as_dict())
def build_transaction(
self,
buy_order: Tuple0x260219a2,
sell_order: Tuple0x260219a2,
buy_signature: Union[bytes, str],
sell_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(
buy_order,
sell_order,
buy_signature,
sell_signature,
) = self.validate_and_normalize_inputs(
buy_order, sell_order, buy_signature, sell_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
buy_order, sell_order, buy_signature, sell_signature
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
buy_order: Tuple0x260219a2,
sell_order: Tuple0x260219a2,
buy_signature: Union[bytes, str],
sell_signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(
buy_order,
sell_order,
buy_signature,
sell_signature,
) = self.validate_and_normalize_inputs(
buy_order, sell_order, buy_signature, sell_signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
buy_order, sell_order, buy_signature, sell_signature
).estimateGas(tx_params.as_dict())
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class DutchAuction:
"""Wrapper class for DutchAuction Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
get_auction_details: GetAuctionDetailsMethod
"""Constructor-initialized instance of
:class:`GetAuctionDetailsMethod`.
"""
match_orders: MatchOrdersMethod
"""Constructor-initialized instance of
:class:`MatchOrdersMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: DutchAuctionValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = DutchAuctionValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=DutchAuction.abi(),
).functions
self.get_auction_details = GetAuctionDetailsMethod(
web3_or_provider,
contract_address,
functions.getAuctionDetails,
validator,
)
self.match_orders = MatchOrdersMethod(
web3_or_provider,
contract_address,
functions.matchOrders,
validator,
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":false,"inputs":[{"components":[{"name":"makerAddress","type":"address"},{"name":"takerAddress","type":"address"},{"name":"feeRecipientAddress","type":"address"},{"name":"senderAddress","type":"address"},{"name":"makerAssetAmount","type":"uint256"},{"name":"takerAssetAmount","type":"uint256"},{"name":"makerFee","type":"uint256"},{"name":"takerFee","type":"uint256"},{"name":"expirationTimeSeconds","type":"uint256"},{"name":"salt","type":"uint256"},{"name":"makerAssetData","type":"bytes"},{"name":"takerAssetData","type":"bytes"}],"name":"order","type":"tuple"}],"name":"getAuctionDetails","outputs":[{"components":[{"name":"beginTimeSeconds","type":"uint256"},{"name":"endTimeSeconds","type":"uint256"},{"name":"beginAmount","type":"uint256"},{"name":"endAmount","type":"uint256"},{"name":"currentAmount","type":"uint256"},{"name":"currentTimeSeconds","type":"uint256"}],"name":"auctionDetails","type":"tuple"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"components":[{"name":"makerAddress","type":"address"},{"name":"takerAddress","type":"address"},{"name":"feeRecipientAddress","type":"address"},{"name":"senderAddress","type":"address"},{"name":"makerAssetAmount","type":"uint256"},{"name":"takerAssetAmount","type":"uint256"},{"name":"makerFee","type":"uint256"},{"name":"takerFee","type":"uint256"},{"name":"expirationTimeSeconds","type":"uint256"},{"name":"salt","type":"uint256"},{"name":"makerAssetData","type":"bytes"},{"name":"takerAssetData","type":"bytes"}],"name":"buyOrder","type":"tuple"},{"components":[{"name":"makerAddress","type":"address"},{"name":"takerAddress","type":"address"},{"name":"feeRecipientAddress","type":"address"},{"name":"senderAddress","type":"address"},{"name":"makerAssetAmount","type":"uint256"},{"name":"takerAssetAmount","type":"uint256"},{"name":"makerFee","type":"uint256"},{"name":"takerFee","type":"uint256"},{"name":"expirationTimeSeconds","type":"uint256"},{"name":"salt","type":"uint256"},{"name":"makerAssetData","type":"bytes"},{"name":"takerAssetData","type":"bytes"}],"name":"sellOrder","type":"tuple"},{"name":"buySignature","type":"bytes"},{"name":"sellSignature","type":"bytes"}],"name":"matchOrders","outputs":[{"components":[{"components":[{"name":"makerAssetFilledAmount","type":"uint256"},{"name":"takerAssetFilledAmount","type":"uint256"},{"name":"makerFeePaid","type":"uint256"},{"name":"takerFeePaid","type":"uint256"}],"name":"left","type":"tuple"},{"components":[{"name":"makerAssetFilledAmount","type":"uint256"},{"name":"takerAssetFilledAmount","type":"uint256"},{"name":"makerFeePaid","type":"uint256"},{"name":"takerFeePaid","type":"uint256"}],"name":"right","type":"tuple"},{"name":"leftMakerAssetSpreadAmount","type":"uint256"}],"name":"matchedFillResults","type":"tuple"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_exchange","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/dutch_auction/__init__.py | __init__.py |
"""Generated wrapper for ZrxVault Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ZrxVault below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ZrxVaultValidator,
)
except ImportError:
class ZrxVaultValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class AddAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the addAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the addAuthorizedAddress method."""
self.validator.assert_valid(
method_name="addAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Authorizes an address.
:param target: Address to authorize.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class AuthoritiesMethod(ContractMethod):
"""Various interfaces to the authorities method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the authorities method."""
self.validator.assert_valid(
method_name="authorities",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class AuthorizedMethod(ContractMethod):
"""Various interfaces to the authorized method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the authorized method."""
self.validator.assert_valid(
method_name="authorized",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, staker: str):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="staker",
argument_value=staker,
)
staker = self.validate_and_checksum_address(staker)
return staker
def call(self, staker: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Returns the balance in Zrx Tokens of the `staker`
:param tx_params: transaction parameters
:returns: Balance in Zrx.
"""
(staker) = self.validate_and_normalize_inputs(staker)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(staker).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, staker: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(staker) = self.validate_and_normalize_inputs(staker)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker).estimateGas(tx_params.as_dict())
class BalanceOfZrxVaultMethod(ContractMethod):
"""Various interfaces to the balanceOfZrxVault method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Returns the entire balance of Zrx tokens in the vault.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class DepositFromMethod(ContractMethod):
"""Various interfaces to the depositFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, staker: str, amount: int):
"""Validate the inputs to the depositFrom method."""
self.validator.assert_valid(
method_name="depositFrom",
parameter_name="staker",
argument_value=staker,
)
staker = self.validate_and_checksum_address(staker)
self.validator.assert_valid(
method_name="depositFrom",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return (staker, amount)
def call(
self, staker: str, amount: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Deposit an `amount` of Zrx Tokens from `staker` into the vault. Note
that only the Staking contract can call this. Note that this can only
be called when *not* in Catastrophic Failure mode.
:param amount: of Zrx Tokens to deposit.
:param staker: of Zrx Tokens.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(staker, amount) = self.validate_and_normalize_inputs(staker, amount)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(staker, amount).call(tx_params.as_dict())
def send_transaction(
self, staker: str, amount: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Deposit an `amount` of Zrx Tokens from `staker` into the vault. Note
that only the Staking contract can call this. Note that this can only
be called when *not* in Catastrophic Failure mode.
:param amount: of Zrx Tokens to deposit.
:param staker: of Zrx Tokens.
:param tx_params: transaction parameters
"""
(staker, amount) = self.validate_and_normalize_inputs(staker, amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker, amount).transact(
tx_params.as_dict()
)
def build_transaction(
self, staker: str, amount: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(staker, amount) = self.validate_and_normalize_inputs(staker, amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker, amount).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, staker: str, amount: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(staker, amount) = self.validate_and_normalize_inputs(staker, amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker, amount).estimateGas(
tx_params.as_dict()
)
class EnterCatastrophicFailureMethod(ContractMethod):
"""Various interfaces to the enterCatastrophicFailure method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Vault enters into Catastrophic Failure Mode. *** WARNING - ONCE IN
CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! *** Note that only
the contract owner can call this function.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method().call(tx_params.as_dict())
def send_transaction(
self, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Vault enters into Catastrophic Failure Mode. *** WARNING - ONCE IN
CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! *** Note that only
the contract owner can call this function.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().transact(tx_params.as_dict())
def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict:
"""Construct calldata to be used as input to the method."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().buildTransaction(tx_params.as_dict())
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class GetAuthorizedAddressesMethod(ContractMethod):
"""Various interfaces to the getAuthorizedAddresses method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> List[str]:
"""Execute underlying contract method via eth_call.
Gets all authorized addresses.
:param tx_params: transaction parameters
:returns: Array of authorized addresses.
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return [str(element) for element in returned]
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class IsInCatastrophicFailureMethod(ContractMethod):
"""Various interfaces to the isInCatastrophicFailure method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return bool(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class OwnerMethod(ContractMethod):
"""Various interfaces to the owner method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str):
"""Validate the inputs to the removeAuthorizedAddress method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddress",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
return target
def call(self, target: str, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target).call(tx_params.as_dict())
def send_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).transact(tx_params.as_dict())
def build_transaction(
self, target: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target) = self.validate_and_normalize_inputs(target)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target).estimateGas(tx_params.as_dict())
class RemoveAuthorizedAddressAtIndexMethod(ContractMethod):
"""Various interfaces to the removeAuthorizedAddressAtIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, target: str, index: int):
"""Validate the inputs to the removeAuthorizedAddressAtIndex method."""
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="target",
argument_value=target,
)
target = self.validate_and_checksum_address(target)
self.validator.assert_valid(
method_name="removeAuthorizedAddressAtIndex",
parameter_name="index",
argument_value=index,
)
# safeguard against fractional inputs
index = int(index)
return (target, index)
def call(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(target, index).call(tx_params.as_dict())
def send_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Removes authorizion of an address.
:param index: Index of target in authorities array.
:param target: Address to remove authorization from.
:param tx_params: transaction parameters
"""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).transact(
tx_params.as_dict()
)
def build_transaction(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, target: str, index: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(target, index) = self.validate_and_normalize_inputs(target, index)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(target, index).estimateGas(
tx_params.as_dict()
)
class SetStakingProxyMethod(ContractMethod):
"""Various interfaces to the setStakingProxy method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _staking_proxy_address: str):
"""Validate the inputs to the setStakingProxy method."""
self.validator.assert_valid(
method_name="setStakingProxy",
parameter_name="_stakingProxyAddress",
argument_value=_staking_proxy_address,
)
_staking_proxy_address = self.validate_and_checksum_address(
_staking_proxy_address
)
return _staking_proxy_address
def call(
self, _staking_proxy_address: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Sets the address of the StakingProxy contract. Note that only the
contract owner can call this function.
:param _stakingProxyAddress: Address of Staking proxy contract.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_staking_proxy_address) = self.validate_and_normalize_inputs(
_staking_proxy_address
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_staking_proxy_address).call(
tx_params.as_dict()
)
def send_transaction(
self, _staking_proxy_address: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Sets the address of the StakingProxy contract. Note that only the
contract owner can call this function.
:param _stakingProxyAddress: Address of Staking proxy contract.
:param tx_params: transaction parameters
"""
(_staking_proxy_address) = self.validate_and_normalize_inputs(
_staking_proxy_address
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_staking_proxy_address).transact(
tx_params.as_dict()
)
def build_transaction(
self, _staking_proxy_address: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_staking_proxy_address) = self.validate_and_normalize_inputs(
_staking_proxy_address
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_staking_proxy_address
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self, _staking_proxy_address: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_staking_proxy_address) = self.validate_and_normalize_inputs(
_staking_proxy_address
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_staking_proxy_address).estimateGas(
tx_params.as_dict()
)
class SetZrxProxyMethod(ContractMethod):
"""Various interfaces to the setZrxProxy method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _zrx_proxy_address: str):
"""Validate the inputs to the setZrxProxy method."""
self.validator.assert_valid(
method_name="setZrxProxy",
parameter_name="_zrxProxyAddress",
argument_value=_zrx_proxy_address,
)
_zrx_proxy_address = self.validate_and_checksum_address(
_zrx_proxy_address
)
return _zrx_proxy_address
def call(
self, _zrx_proxy_address: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Sets the Zrx proxy. Note that only an authorized address can call this
function. Note that this can only be called when *not* in Catastrophic
Failure mode.
:param _zrxProxyAddress: Address of the 0x Zrx Proxy.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_zrx_proxy_address) = self.validate_and_normalize_inputs(
_zrx_proxy_address
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_zrx_proxy_address).call(tx_params.as_dict())
def send_transaction(
self, _zrx_proxy_address: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Sets the Zrx proxy. Note that only an authorized address can call this
function. Note that this can only be called when *not* in Catastrophic
Failure mode.
:param _zrxProxyAddress: Address of the 0x Zrx Proxy.
:param tx_params: transaction parameters
"""
(_zrx_proxy_address) = self.validate_and_normalize_inputs(
_zrx_proxy_address
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_zrx_proxy_address).transact(
tx_params.as_dict()
)
def build_transaction(
self, _zrx_proxy_address: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_zrx_proxy_address) = self.validate_and_normalize_inputs(
_zrx_proxy_address
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_zrx_proxy_address).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _zrx_proxy_address: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_zrx_proxy_address) = self.validate_and_normalize_inputs(
_zrx_proxy_address
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_zrx_proxy_address).estimateGas(
tx_params.as_dict()
)
class StakingProxyAddressMethod(ContractMethod):
"""Various interfaces to the stakingProxyAddress method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferOwnershipMethod(ContractMethod):
"""Various interfaces to the transferOwnership method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, new_owner: str):
"""Validate the inputs to the transferOwnership method."""
self.validator.assert_valid(
method_name="transferOwnership",
parameter_name="newOwner",
argument_value=new_owner,
)
new_owner = self.validate_and_checksum_address(new_owner)
return new_owner
def call(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(new_owner).call(tx_params.as_dict())
def send_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).transact(tx_params.as_dict())
def build_transaction(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, new_owner: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(new_owner) = self.validate_and_normalize_inputs(new_owner)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(new_owner).estimateGas(
tx_params.as_dict()
)
class WithdrawAllFromMethod(ContractMethod):
"""Various interfaces to the withdrawAllFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, staker: str):
"""Validate the inputs to the withdrawAllFrom method."""
self.validator.assert_valid(
method_name="withdrawAllFrom",
parameter_name="staker",
argument_value=staker,
)
staker = self.validate_and_checksum_address(staker)
return staker
def call(self, staker: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Withdraw ALL Zrx Tokens to `staker` from the vault. Note that this can
only be called when *in* Catastrophic Failure mode.
:param staker: of Zrx Tokens.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(staker) = self.validate_and_normalize_inputs(staker)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(staker).call(tx_params.as_dict())
return int(returned)
def send_transaction(
self, staker: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Withdraw ALL Zrx Tokens to `staker` from the vault. Note that this can
only be called when *in* Catastrophic Failure mode.
:param staker: of Zrx Tokens.
:param tx_params: transaction parameters
"""
(staker) = self.validate_and_normalize_inputs(staker)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker).transact(tx_params.as_dict())
def build_transaction(
self, staker: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(staker) = self.validate_and_normalize_inputs(staker)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, staker: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(staker) = self.validate_and_normalize_inputs(staker)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker).estimateGas(tx_params.as_dict())
class WithdrawFromMethod(ContractMethod):
"""Various interfaces to the withdrawFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, staker: str, amount: int):
"""Validate the inputs to the withdrawFrom method."""
self.validator.assert_valid(
method_name="withdrawFrom",
parameter_name="staker",
argument_value=staker,
)
staker = self.validate_and_checksum_address(staker)
self.validator.assert_valid(
method_name="withdrawFrom",
parameter_name="amount",
argument_value=amount,
)
# safeguard against fractional inputs
amount = int(amount)
return (staker, amount)
def call(
self, staker: str, amount: int, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Withdraw an `amount` of Zrx Tokens to `staker` from the vault. Note
that only the Staking contract can call this. Note that this can only
be called when *not* in Catastrophic Failure mode.
:param amount: of Zrx Tokens to withdraw.
:param staker: of Zrx Tokens.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(staker, amount) = self.validate_and_normalize_inputs(staker, amount)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(staker, amount).call(tx_params.as_dict())
def send_transaction(
self, staker: str, amount: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Withdraw an `amount` of Zrx Tokens to `staker` from the vault. Note
that only the Staking contract can call this. Note that this can only
be called when *not* in Catastrophic Failure mode.
:param amount: of Zrx Tokens to withdraw.
:param staker: of Zrx Tokens.
:param tx_params: transaction parameters
"""
(staker, amount) = self.validate_and_normalize_inputs(staker, amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker, amount).transact(
tx_params.as_dict()
)
def build_transaction(
self, staker: str, amount: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(staker, amount) = self.validate_and_normalize_inputs(staker, amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker, amount).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, staker: str, amount: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(staker, amount) = self.validate_and_normalize_inputs(staker, amount)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(staker, amount).estimateGas(
tx_params.as_dict()
)
class ZrxAssetProxyMethod(ContractMethod):
"""Various interfaces to the zrxAssetProxy method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ZrxVault:
"""Wrapper class for ZrxVault Solidity contract."""
add_authorized_address: AddAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`AddAuthorizedAddressMethod`.
"""
authorities: AuthoritiesMethod
"""Constructor-initialized instance of
:class:`AuthoritiesMethod`.
"""
authorized: AuthorizedMethod
"""Constructor-initialized instance of
:class:`AuthorizedMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
balance_of_zrx_vault: BalanceOfZrxVaultMethod
"""Constructor-initialized instance of
:class:`BalanceOfZrxVaultMethod`.
"""
deposit_from: DepositFromMethod
"""Constructor-initialized instance of
:class:`DepositFromMethod`.
"""
enter_catastrophic_failure: EnterCatastrophicFailureMethod
"""Constructor-initialized instance of
:class:`EnterCatastrophicFailureMethod`.
"""
get_authorized_addresses: GetAuthorizedAddressesMethod
"""Constructor-initialized instance of
:class:`GetAuthorizedAddressesMethod`.
"""
is_in_catastrophic_failure: IsInCatastrophicFailureMethod
"""Constructor-initialized instance of
:class:`IsInCatastrophicFailureMethod`.
"""
owner: OwnerMethod
"""Constructor-initialized instance of
:class:`OwnerMethod`.
"""
remove_authorized_address: RemoveAuthorizedAddressMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressMethod`.
"""
remove_authorized_address_at_index: RemoveAuthorizedAddressAtIndexMethod
"""Constructor-initialized instance of
:class:`RemoveAuthorizedAddressAtIndexMethod`.
"""
set_staking_proxy: SetStakingProxyMethod
"""Constructor-initialized instance of
:class:`SetStakingProxyMethod`.
"""
set_zrx_proxy: SetZrxProxyMethod
"""Constructor-initialized instance of
:class:`SetZrxProxyMethod`.
"""
staking_proxy_address: StakingProxyAddressMethod
"""Constructor-initialized instance of
:class:`StakingProxyAddressMethod`.
"""
transfer_ownership: TransferOwnershipMethod
"""Constructor-initialized instance of
:class:`TransferOwnershipMethod`.
"""
withdraw_all_from: WithdrawAllFromMethod
"""Constructor-initialized instance of
:class:`WithdrawAllFromMethod`.
"""
withdraw_from: WithdrawFromMethod
"""Constructor-initialized instance of
:class:`WithdrawFromMethod`.
"""
zrx_asset_proxy: ZrxAssetProxyMethod
"""Constructor-initialized instance of
:class:`ZrxAssetProxyMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ZrxVaultValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ZrxVaultValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=ZrxVault.abi()
).functions
self.add_authorized_address = AddAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.addAuthorizedAddress,
validator,
)
self.authorities = AuthoritiesMethod(
web3_or_provider,
contract_address,
functions.authorities,
validator,
)
self.authorized = AuthorizedMethod(
web3_or_provider, contract_address, functions.authorized, validator
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.balance_of_zrx_vault = BalanceOfZrxVaultMethod(
web3_or_provider, contract_address, functions.balanceOfZrxVault
)
self.deposit_from = DepositFromMethod(
web3_or_provider,
contract_address,
functions.depositFrom,
validator,
)
self.enter_catastrophic_failure = EnterCatastrophicFailureMethod(
web3_or_provider,
contract_address,
functions.enterCatastrophicFailure,
)
self.get_authorized_addresses = GetAuthorizedAddressesMethod(
web3_or_provider,
contract_address,
functions.getAuthorizedAddresses,
)
self.is_in_catastrophic_failure = IsInCatastrophicFailureMethod(
web3_or_provider,
contract_address,
functions.isInCatastrophicFailure,
)
self.owner = OwnerMethod(
web3_or_provider, contract_address, functions.owner
)
self.remove_authorized_address = RemoveAuthorizedAddressMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddress,
validator,
)
self.remove_authorized_address_at_index = RemoveAuthorizedAddressAtIndexMethod(
web3_or_provider,
contract_address,
functions.removeAuthorizedAddressAtIndex,
validator,
)
self.set_staking_proxy = SetStakingProxyMethod(
web3_or_provider,
contract_address,
functions.setStakingProxy,
validator,
)
self.set_zrx_proxy = SetZrxProxyMethod(
web3_or_provider,
contract_address,
functions.setZrxProxy,
validator,
)
self.staking_proxy_address = StakingProxyAddressMethod(
web3_or_provider, contract_address, functions.stakingProxyAddress
)
self.transfer_ownership = TransferOwnershipMethod(
web3_or_provider,
contract_address,
functions.transferOwnership,
validator,
)
self.withdraw_all_from = WithdrawAllFromMethod(
web3_or_provider,
contract_address,
functions.withdrawAllFrom,
validator,
)
self.withdraw_from = WithdrawFromMethod(
web3_or_provider,
contract_address,
functions.withdrawFrom,
validator,
)
self.zrx_asset_proxy = ZrxAssetProxyMethod(
web3_or_provider, contract_address, functions.zrxAssetProxy
)
def get_authorized_address_added_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressAdded event.
:param tx_hash: hash of transaction emitting AuthorizedAddressAdded
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZrxVault.abi(),
)
.events.AuthorizedAddressAdded()
.processReceipt(tx_receipt)
)
def get_authorized_address_removed_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for AuthorizedAddressRemoved event.
:param tx_hash: hash of transaction emitting AuthorizedAddressRemoved
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZrxVault.abi(),
)
.events.AuthorizedAddressRemoved()
.processReceipt(tx_receipt)
)
def get_deposit_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Deposit event.
:param tx_hash: hash of transaction emitting Deposit event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZrxVault.abi(),
)
.events.Deposit()
.processReceipt(tx_receipt)
)
def get_in_catastrophic_failure_mode_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for InCatastrophicFailureMode event.
:param tx_hash: hash of transaction emitting InCatastrophicFailureMode
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZrxVault.abi(),
)
.events.InCatastrophicFailureMode()
.processReceipt(tx_receipt)
)
def get_ownership_transferred_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for OwnershipTransferred event.
:param tx_hash: hash of transaction emitting OwnershipTransferred event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZrxVault.abi(),
)
.events.OwnershipTransferred()
.processReceipt(tx_receipt)
)
def get_staking_proxy_set_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for StakingProxySet event.
:param tx_hash: hash of transaction emitting StakingProxySet event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZrxVault.abi(),
)
.events.StakingProxySet()
.processReceipt(tx_receipt)
)
def get_withdraw_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Withdraw event.
:param tx_hash: hash of transaction emitting Withdraw event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZrxVault.abi(),
)
.events.Withdraw()
.processReceipt(tx_receipt)
)
def get_zrx_proxy_set_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ZrxProxySet event.
:param tx_hash: hash of transaction emitting ZrxProxySet event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ZrxVault.abi(),
)
.events.ZrxProxySet()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[{"internalType":"address","name":"_zrxProxyAddress","type":"address"},{"internalType":"address","name":"_zrxTokenAddress","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"AuthorizedAddressRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"staker","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"}],"name":"InCatastrophicFailureMode","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"stakingProxyAddress","type":"address"}],"name":"StakingProxySet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"staker","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"zrxProxyAddress","type":"address"}],"name":"ZrxProxySet","type":"event"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"addAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"authorities","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"index_0","type":"address"}],"name":"authorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"staker","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"balanceOfZrxVault","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"staker","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"enterCatastrophicFailure","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getAuthorizedAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isInCatastrophicFailure","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"removeAuthorizedAddress","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"removeAuthorizedAddressAtIndex","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_stakingProxyAddress","type":"address"}],"name":"setStakingProxy","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_zrxProxyAddress","type":"address"}],"name":"setZrxProxy","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"stakingProxyAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"staker","type":"address"}],"name":"withdrawAllFrom","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"staker","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"zrxAssetProxy","outputs":[{"internalType":"contract IAssetProxy","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/zrx_vault/__init__.py | __init__.py |
"""Generated wrapper for EthBalanceChecker Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for EthBalanceChecker below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
EthBalanceCheckerValidator,
)
except ImportError:
class EthBalanceCheckerValidator( # type: ignore
Validator
):
"""No-op input validator."""
class GetEthBalancesMethod(ContractMethod):
"""Various interfaces to the getEthBalances method."""
def __init__(
self,
provider: BaseProvider,
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, addresses: List[str]):
"""Validate the inputs to the getEthBalances method."""
self.validator.assert_valid(
method_name="getEthBalances",
parameter_name="addresses",
argument_value=addresses,
)
return addresses
def call(
self, addresses: List[str], tx_params: Optional[TxParams] = None
) -> List[int]:
"""Execute underlying contract method via eth_call.
Batch fetches ETH balances
:param addresses: Array of addresses.
:param tx_params: transaction parameters
:returns: Array of ETH balances.
"""
(addresses) = self.validate_and_normalize_inputs(addresses)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addresses).call(tx_params.as_dict())
def send_transaction(
self, addresses: List[str], tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Batch fetches ETH balances
:param addresses: Array of addresses.
:param tx_params: transaction parameters
:returns: Array of ETH balances.
"""
(addresses) = self.validate_and_normalize_inputs(addresses)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addresses).transact(tx_params.as_dict())
def estimate_gas(
self, addresses: List[str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(addresses) = self.validate_and_normalize_inputs(addresses)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addresses).estimateGas(
tx_params.as_dict()
)
def build_transaction(
self, addresses: List[str], tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(addresses) = self.validate_and_normalize_inputs(addresses)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(addresses).buildTransaction(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class EthBalanceChecker:
"""Wrapper class for EthBalanceChecker Solidity contract."""
get_eth_balances: GetEthBalancesMethod
"""Constructor-initialized instance of
:class:`GetEthBalancesMethod`.
"""
def __init__(
self,
provider: BaseProvider,
contract_address: str,
validator: EthBalanceCheckerValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param provider: instance of :class:`web3.providers.base.BaseProvider`
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
self.contract_address = contract_address
if not validator:
validator = EthBalanceCheckerValidator(provider, contract_address)
self._web3_eth = Web3( # type: ignore # pylint: disable=no-member
provider
).eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=EthBalanceChecker.abi(),
).functions
self.get_eth_balances = GetEthBalancesMethod(
provider, contract_address, functions.getEthBalances, validator
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":true,"inputs":[{"name":"addresses","type":"address[]"}],"name":"getEthBalances","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/eth_balance_checker/__init__.py | __init__.py |
"""Generated wrapper for ERC1155Mintable Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for ERC1155Mintable below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
ERC1155MintableValidator,
)
except ImportError:
class ERC1155MintableValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class Erc1155BatchReceivedMethod(ContractMethod):
"""Various interfaces to the ERC1155_BATCH_RECEIVED method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class Erc1155ReceivedMethod(ContractMethod):
"""Various interfaces to the ERC1155_RECEIVED method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return Union[bytes, str](returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, owner: str, _id: int):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="owner",
argument_value=owner,
)
owner = self.validate_and_checksum_address(owner)
self.validator.assert_valid(
method_name="balanceOf", parameter_name="id", argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
return (owner, _id)
def call(
self, owner: str, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param id: ID of the Token
:param owner: The address of the token holder
:param tx_params: transaction parameters
:returns: The _owner's balance of the Token type requested
"""
(owner, _id) = self.validate_and_normalize_inputs(owner, _id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner, _id).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self, owner: str, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(owner, _id) = self.validate_and_normalize_inputs(owner, _id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner, _id).estimateGas(
tx_params.as_dict()
)
class BalanceOfBatchMethod(ContractMethod):
"""Various interfaces to the balanceOfBatch method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, owners: List[str], ids: List[int]):
"""Validate the inputs to the balanceOfBatch method."""
self.validator.assert_valid(
method_name="balanceOfBatch",
parameter_name="owners",
argument_value=owners,
)
self.validator.assert_valid(
method_name="balanceOfBatch",
parameter_name="ids",
argument_value=ids,
)
return (owners, ids)
def call(
self,
owners: List[str],
ids: List[int],
tx_params: Optional[TxParams] = None,
) -> List[int]:
"""Execute underlying contract method via eth_call.
:param ids: ID of the Tokens
:param owners: The addresses of the token holders
:param tx_params: transaction parameters
:returns: The _owner's balance of the Token types requested
"""
(owners, ids) = self.validate_and_normalize_inputs(owners, ids)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owners, ids).call(
tx_params.as_dict()
)
return [int(element) for element in returned]
def estimate_gas(
self,
owners: List[str],
ids: List[int],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(owners, ids) = self.validate_and_normalize_inputs(owners, ids)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owners, ids).estimateGas(
tx_params.as_dict()
)
class CreateMethod(ContractMethod):
"""Various interfaces to the create method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, uri: str, is_nf: bool):
"""Validate the inputs to the create method."""
self.validator.assert_valid(
method_name="create", parameter_name="uri", argument_value=uri,
)
self.validator.assert_valid(
method_name="create", parameter_name="isNF", argument_value=is_nf,
)
return (uri, is_nf)
def call(
self, uri: str, is_nf: bool, tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
creates a new token
:param isNF: is non-fungible token
:param uri: URI of token
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(uri, is_nf) = self.validate_and_normalize_inputs(uri, is_nf)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(uri, is_nf).call(
tx_params.as_dict()
)
return int(returned)
def send_transaction(
self, uri: str, is_nf: bool, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
creates a new token
:param isNF: is non-fungible token
:param uri: URI of token
:param tx_params: transaction parameters
"""
(uri, is_nf) = self.validate_and_normalize_inputs(uri, is_nf)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(uri, is_nf).transact(
tx_params.as_dict()
)
def build_transaction(
self, uri: str, is_nf: bool, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(uri, is_nf) = self.validate_and_normalize_inputs(uri, is_nf)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(uri, is_nf).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, uri: str, is_nf: bool, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(uri, is_nf) = self.validate_and_normalize_inputs(uri, is_nf)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(uri, is_nf).estimateGas(
tx_params.as_dict()
)
class CreateWithTypeMethod(ContractMethod):
"""Various interfaces to the createWithType method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _type: int, uri: str):
"""Validate the inputs to the createWithType method."""
self.validator.assert_valid(
method_name="createWithType",
parameter_name="type_",
argument_value=_type,
)
# safeguard against fractional inputs
_type = int(_type)
self.validator.assert_valid(
method_name="createWithType",
parameter_name="uri",
argument_value=uri,
)
return (_type, uri)
def call(
self, _type: int, uri: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
creates a new token
:param type_: of token
:param uri: URI of token
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_type, uri) = self.validate_and_normalize_inputs(_type, uri)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_type, uri).call(tx_params.as_dict())
def send_transaction(
self, _type: int, uri: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
creates a new token
:param type_: of token
:param uri: URI of token
:param tx_params: transaction parameters
"""
(_type, uri) = self.validate_and_normalize_inputs(_type, uri)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_type, uri).transact(
tx_params.as_dict()
)
def build_transaction(
self, _type: int, uri: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_type, uri) = self.validate_and_normalize_inputs(_type, uri)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_type, uri).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _type: int, uri: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_type, uri) = self.validate_and_normalize_inputs(_type, uri)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_type, uri).estimateGas(
tx_params.as_dict()
)
class CreatorsMethod(ContractMethod):
"""Various interfaces to the creators method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the creators method."""
self.validator.assert_valid(
method_name="creators",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class GetNonFungibleBaseTypeMethod(ContractMethod):
"""Various interfaces to the getNonFungibleBaseType method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _id: int):
"""Validate the inputs to the getNonFungibleBaseType method."""
self.validator.assert_valid(
method_name="getNonFungibleBaseType",
parameter_name="id",
argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
return _id
def call(self, _id: int, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Returns base type of non-fungible token
:param tx_params: transaction parameters
"""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_id).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id).estimateGas(tx_params.as_dict())
class GetNonFungibleIndexMethod(ContractMethod):
"""Various interfaces to the getNonFungibleIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _id: int):
"""Validate the inputs to the getNonFungibleIndex method."""
self.validator.assert_valid(
method_name="getNonFungibleIndex",
parameter_name="id",
argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
return _id
def call(self, _id: int, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
Returns index of non-fungible token
:param tx_params: transaction parameters
"""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_id).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id).estimateGas(tx_params.as_dict())
class IsApprovedForAllMethod(ContractMethod):
"""Various interfaces to the isApprovedForAll method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, owner: str, operator: str):
"""Validate the inputs to the isApprovedForAll method."""
self.validator.assert_valid(
method_name="isApprovedForAll",
parameter_name="owner",
argument_value=owner,
)
owner = self.validate_and_checksum_address(owner)
self.validator.assert_valid(
method_name="isApprovedForAll",
parameter_name="operator",
argument_value=operator,
)
operator = self.validate_and_checksum_address(operator)
return (owner, operator)
def call(
self, owner: str, operator: str, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param operator: Address of authorized operator
:param owner: The owner of the Tokens
:param tx_params: transaction parameters
:returns: True if the operator is approved, false if not
"""
(owner, operator) = self.validate_and_normalize_inputs(owner, operator)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(owner, operator).call(
tx_params.as_dict()
)
return bool(returned)
def estimate_gas(
self, owner: str, operator: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(owner, operator) = self.validate_and_normalize_inputs(owner, operator)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(owner, operator).estimateGas(
tx_params.as_dict()
)
class IsFungibleMethod(ContractMethod):
"""Various interfaces to the isFungible method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _id: int):
"""Validate the inputs to the isFungible method."""
self.validator.assert_valid(
method_name="isFungible", parameter_name="id", argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
return _id
def call(self, _id: int, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
Returns true if token is fungible
:param tx_params: transaction parameters
"""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_id).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id).estimateGas(tx_params.as_dict())
class IsNonFungibleMethod(ContractMethod):
"""Various interfaces to the isNonFungible method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _id: int):
"""Validate the inputs to the isNonFungible method."""
self.validator.assert_valid(
method_name="isNonFungible",
parameter_name="id",
argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
return _id
def call(self, _id: int, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
Returns true if token is non-fungible
:param tx_params: transaction parameters
"""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_id).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id).estimateGas(tx_params.as_dict())
class IsNonFungibleBaseTypeMethod(ContractMethod):
"""Various interfaces to the isNonFungibleBaseType method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _id: int):
"""Validate the inputs to the isNonFungibleBaseType method."""
self.validator.assert_valid(
method_name="isNonFungibleBaseType",
parameter_name="id",
argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
return _id
def call(self, _id: int, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
Returns true if input is base-type of a non-fungible token
:param tx_params: transaction parameters
"""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_id).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id).estimateGas(tx_params.as_dict())
class IsNonFungibleItemMethod(ContractMethod):
"""Various interfaces to the isNonFungibleItem method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _id: int):
"""Validate the inputs to the isNonFungibleItem method."""
self.validator.assert_valid(
method_name="isNonFungibleItem",
parameter_name="id",
argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
return _id
def call(self, _id: int, tx_params: Optional[TxParams] = None) -> bool:
"""Execute underlying contract method via eth_call.
Returns true if input is a non-fungible token
:param tx_params: transaction parameters
"""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_id).call(tx_params.as_dict())
return bool(returned)
def estimate_gas(
self, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id).estimateGas(tx_params.as_dict())
class MaxIndexMethod(ContractMethod):
"""Various interfaces to the maxIndex method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: int):
"""Validate the inputs to the maxIndex method."""
self.validator.assert_valid(
method_name="maxIndex",
parameter_name="index_0",
argument_value=index_0,
)
# safeguard against fractional inputs
index_0 = int(index_0)
return index_0
def call(self, index_0: int, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, index_0: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class MintFungibleMethod(ContractMethod):
"""Various interfaces to the mintFungible method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _id: int, to: List[str], quantities: List[int]
):
"""Validate the inputs to the mintFungible method."""
self.validator.assert_valid(
method_name="mintFungible",
parameter_name="id",
argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
self.validator.assert_valid(
method_name="mintFungible", parameter_name="to", argument_value=to,
)
self.validator.assert_valid(
method_name="mintFungible",
parameter_name="quantities",
argument_value=quantities,
)
return (_id, to, quantities)
def call(
self,
_id: int,
to: List[str],
quantities: List[int],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
mints fungible tokens
:param id: token type
:param quantities: amounts of minted tokens
:param to: beneficiaries of minted tokens
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_id, to, quantities) = self.validate_and_normalize_inputs(
_id, to, quantities
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_id, to, quantities).call(tx_params.as_dict())
def send_transaction(
self,
_id: int,
to: List[str],
quantities: List[int],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
mints fungible tokens
:param id: token type
:param quantities: amounts of minted tokens
:param to: beneficiaries of minted tokens
:param tx_params: transaction parameters
"""
(_id, to, quantities) = self.validate_and_normalize_inputs(
_id, to, quantities
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id, to, quantities).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_id: int,
to: List[str],
quantities: List[int],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_id, to, quantities) = self.validate_and_normalize_inputs(
_id, to, quantities
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id, to, quantities).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
_id: int,
to: List[str],
quantities: List[int],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_id, to, quantities) = self.validate_and_normalize_inputs(
_id, to, quantities
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id, to, quantities).estimateGas(
tx_params.as_dict()
)
class MintNonFungibleMethod(ContractMethod):
"""Various interfaces to the mintNonFungible method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _type: int, to: List[str]):
"""Validate the inputs to the mintNonFungible method."""
self.validator.assert_valid(
method_name="mintNonFungible",
parameter_name="type_",
argument_value=_type,
)
# safeguard against fractional inputs
_type = int(_type)
self.validator.assert_valid(
method_name="mintNonFungible",
parameter_name="to",
argument_value=to,
)
return (_type, to)
def call(
self, _type: int, to: List[str], tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
mints a non-fungible token
:param to: beneficiaries of minted tokens
:param type_: token type
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_type, to) = self.validate_and_normalize_inputs(_type, to)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_type, to).call(tx_params.as_dict())
def send_transaction(
self, _type: int, to: List[str], tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
mints a non-fungible token
:param to: beneficiaries of minted tokens
:param type_: token type
:param tx_params: transaction parameters
"""
(_type, to) = self.validate_and_normalize_inputs(_type, to)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_type, to).transact(tx_params.as_dict())
def build_transaction(
self, _type: int, to: List[str], tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(_type, to) = self.validate_and_normalize_inputs(_type, to)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_type, to).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, _type: int, to: List[str], tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_type, to) = self.validate_and_normalize_inputs(_type, to)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_type, to).estimateGas(
tx_params.as_dict()
)
class OwnerOfMethod(ContractMethod):
"""Various interfaces to the ownerOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, _id: int):
"""Validate the inputs to the ownerOf method."""
self.validator.assert_valid(
method_name="ownerOf", parameter_name="id", argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
return _id
def call(self, _id: int, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
returns owner of a non-fungible token
:param tx_params: transaction parameters
"""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_id).call(tx_params.as_dict())
return str(returned)
def estimate_gas(
self, _id: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(_id) = self.validate_and_normalize_inputs(_id)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_id).estimateGas(tx_params.as_dict())
class SafeBatchTransferFromMethod(ContractMethod):
"""Various interfaces to the safeBatchTransferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
_from: str,
to: str,
ids: List[int],
values: List[int],
data: Union[bytes, str],
):
"""Validate the inputs to the safeBatchTransferFrom method."""
self.validator.assert_valid(
method_name="safeBatchTransferFrom",
parameter_name="from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="safeBatchTransferFrom",
parameter_name="to",
argument_value=to,
)
to = self.validate_and_checksum_address(to)
self.validator.assert_valid(
method_name="safeBatchTransferFrom",
parameter_name="ids",
argument_value=ids,
)
self.validator.assert_valid(
method_name="safeBatchTransferFrom",
parameter_name="values",
argument_value=values,
)
self.validator.assert_valid(
method_name="safeBatchTransferFrom",
parameter_name="data",
argument_value=data,
)
return (_from, to, ids, values, data)
def call(
self,
_from: str,
to: str,
ids: List[int],
values: List[int],
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
MUST emit TransferBatch event on success. Caller must be approved to
manage the _from account's tokens (see isApprovedForAll). MUST throw if
`_to` is the zero address. MUST throw if length of `_ids` is not the
same as length of `_values`. MUST throw if any of the balance of sender
for token `_ids` is lower than the respective `_values` sent. MUST
throw on any other error. When transfer is complete, this function MUST
check if `_to` is a smart contract (code size > 0). If so, it MUST call
`onERC1155BatchReceived` on `_to` and revert if the return value is not
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],ui-
nt256[],bytes)"))`.
:param data: Additional data with no specified format, sent in call to
`_to`
:param from: Source addresses
:param ids: IDs of each token type
:param to: Target addresses
:param values: Transfer amounts per token type
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, to, ids, values, data) = self.validate_and_normalize_inputs(
_from, to, ids, values, data
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, to, ids, values, data).call(
tx_params.as_dict()
)
def send_transaction(
self,
_from: str,
to: str,
ids: List[int],
values: List[int],
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
MUST emit TransferBatch event on success. Caller must be approved to
manage the _from account's tokens (see isApprovedForAll). MUST throw if
`_to` is the zero address. MUST throw if length of `_ids` is not the
same as length of `_values`. MUST throw if any of the balance of sender
for token `_ids` is lower than the respective `_values` sent. MUST
throw on any other error. When transfer is complete, this function MUST
check if `_to` is a smart contract (code size > 0). If so, it MUST call
`onERC1155BatchReceived` on `_to` and revert if the return value is not
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],ui-
nt256[],bytes)"))`.
:param data: Additional data with no specified format, sent in call to
`_to`
:param from: Source addresses
:param ids: IDs of each token type
:param to: Target addresses
:param values: Transfer amounts per token type
:param tx_params: transaction parameters
"""
(_from, to, ids, values, data) = self.validate_and_normalize_inputs(
_from, to, ids, values, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, to, ids, values, data).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
to: str,
ids: List[int],
values: List[int],
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, to, ids, values, data) = self.validate_and_normalize_inputs(
_from, to, ids, values, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, to, ids, values, data
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
_from: str,
to: str,
ids: List[int],
values: List[int],
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, to, ids, values, data) = self.validate_and_normalize_inputs(
_from, to, ids, values, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, to, ids, values, data
).estimateGas(tx_params.as_dict())
class SafeTransferFromMethod(ContractMethod):
"""Various interfaces to the safeTransferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self,
_from: str,
to: str,
_id: int,
value: int,
data: Union[bytes, str],
):
"""Validate the inputs to the safeTransferFrom method."""
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="from",
argument_value=_from,
)
_from = self.validate_and_checksum_address(_from)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="to",
argument_value=to,
)
to = self.validate_and_checksum_address(to)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="id",
argument_value=_id,
)
# safeguard against fractional inputs
_id = int(_id)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="value",
argument_value=value,
)
# safeguard against fractional inputs
value = int(value)
self.validator.assert_valid(
method_name="safeTransferFrom",
parameter_name="data",
argument_value=data,
)
return (_from, to, _id, value, data)
def call(
self,
_from: str,
to: str,
_id: int,
value: int,
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
MUST emit TransferSingle event on success. Caller must be approved to
manage the _from account's tokens (see isApprovedForAll). MUST throw if
`_to` is the zero address. MUST throw if balance of sender for token
`_id` is lower than the `_value` sent. MUST throw on any other error.
When transfer is complete, this function MUST check if `_to` is a smart
contract (code size > 0). If so, it MUST call `onERC1155Received` on
`_to` and revert if the return value is not `bytes4(keccak256("onERC11-
55Received(address,address,uint256,uint256,bytes)"))`.
:param data: Additional data with no specified format, sent in call to
`_to`
:param from: Source address
:param id: ID of the token type
:param to: Target address
:param value: Transfer amount
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(_from, to, _id, value, data) = self.validate_and_normalize_inputs(
_from, to, _id, value, data
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(_from, to, _id, value, data).call(
tx_params.as_dict()
)
def send_transaction(
self,
_from: str,
to: str,
_id: int,
value: int,
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
MUST emit TransferSingle event on success. Caller must be approved to
manage the _from account's tokens (see isApprovedForAll). MUST throw if
`_to` is the zero address. MUST throw if balance of sender for token
`_id` is lower than the `_value` sent. MUST throw on any other error.
When transfer is complete, this function MUST check if `_to` is a smart
contract (code size > 0). If so, it MUST call `onERC1155Received` on
`_to` and revert if the return value is not `bytes4(keccak256("onERC11-
55Received(address,address,uint256,uint256,bytes)"))`.
:param data: Additional data with no specified format, sent in call to
`_to`
:param from: Source address
:param id: ID of the token type
:param to: Target address
:param value: Transfer amount
:param tx_params: transaction parameters
"""
(_from, to, _id, value, data) = self.validate_and_normalize_inputs(
_from, to, _id, value, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_from, to, _id, value, data).transact(
tx_params.as_dict()
)
def build_transaction(
self,
_from: str,
to: str,
_id: int,
value: int,
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(_from, to, _id, value, data) = self.validate_and_normalize_inputs(
_from, to, _id, value, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, to, _id, value, data
).buildTransaction(tx_params.as_dict())
def estimate_gas(
self,
_from: str,
to: str,
_id: int,
value: int,
data: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_from, to, _id, value, data) = self.validate_and_normalize_inputs(
_from, to, _id, value, data
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(
_from, to, _id, value, data
).estimateGas(tx_params.as_dict())
class SetApprovalForAllMethod(ContractMethod):
"""Various interfaces to the setApprovalForAll method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, operator: str, approved: bool):
"""Validate the inputs to the setApprovalForAll method."""
self.validator.assert_valid(
method_name="setApprovalForAll",
parameter_name="operator",
argument_value=operator,
)
operator = self.validate_and_checksum_address(operator)
self.validator.assert_valid(
method_name="setApprovalForAll",
parameter_name="approved",
argument_value=approved,
)
return (operator, approved)
def call(
self,
operator: str,
approved: bool,
tx_params: Optional[TxParams] = None,
) -> None:
"""Execute underlying contract method via eth_call.
MUST emit the ApprovalForAll event on success.
:param approved: True if the operator is approved, false to revoke
approval
:param operator: Address to add to the set of authorized operators
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(operator, approved) = self.validate_and_normalize_inputs(
operator, approved
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(operator, approved).call(tx_params.as_dict())
def send_transaction(
self,
operator: str,
approved: bool,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
MUST emit the ApprovalForAll event on success.
:param approved: True if the operator is approved, false to revoke
approval
:param operator: Address to add to the set of authorized operators
:param tx_params: transaction parameters
"""
(operator, approved) = self.validate_and_normalize_inputs(
operator, approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(operator, approved).transact(
tx_params.as_dict()
)
def build_transaction(
self,
operator: str,
approved: bool,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(operator, approved) = self.validate_and_normalize_inputs(
operator, approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(operator, approved).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
operator: str,
approved: bool,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(operator, approved) = self.validate_and_normalize_inputs(
operator, approved
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(operator, approved).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class ERC1155Mintable:
"""Wrapper class for ERC1155Mintable Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
erc1155_batch_received: Erc1155BatchReceivedMethod
"""Constructor-initialized instance of
:class:`Erc1155BatchReceivedMethod`.
"""
erc1155_received: Erc1155ReceivedMethod
"""Constructor-initialized instance of
:class:`Erc1155ReceivedMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
balance_of_batch: BalanceOfBatchMethod
"""Constructor-initialized instance of
:class:`BalanceOfBatchMethod`.
"""
create: CreateMethod
"""Constructor-initialized instance of
:class:`CreateMethod`.
"""
create_with_type: CreateWithTypeMethod
"""Constructor-initialized instance of
:class:`CreateWithTypeMethod`.
"""
creators: CreatorsMethod
"""Constructor-initialized instance of
:class:`CreatorsMethod`.
"""
get_non_fungible_base_type: GetNonFungibleBaseTypeMethod
"""Constructor-initialized instance of
:class:`GetNonFungibleBaseTypeMethod`.
"""
get_non_fungible_index: GetNonFungibleIndexMethod
"""Constructor-initialized instance of
:class:`GetNonFungibleIndexMethod`.
"""
is_approved_for_all: IsApprovedForAllMethod
"""Constructor-initialized instance of
:class:`IsApprovedForAllMethod`.
"""
is_fungible: IsFungibleMethod
"""Constructor-initialized instance of
:class:`IsFungibleMethod`.
"""
is_non_fungible: IsNonFungibleMethod
"""Constructor-initialized instance of
:class:`IsNonFungibleMethod`.
"""
is_non_fungible_base_type: IsNonFungibleBaseTypeMethod
"""Constructor-initialized instance of
:class:`IsNonFungibleBaseTypeMethod`.
"""
is_non_fungible_item: IsNonFungibleItemMethod
"""Constructor-initialized instance of
:class:`IsNonFungibleItemMethod`.
"""
max_index: MaxIndexMethod
"""Constructor-initialized instance of
:class:`MaxIndexMethod`.
"""
mint_fungible: MintFungibleMethod
"""Constructor-initialized instance of
:class:`MintFungibleMethod`.
"""
mint_non_fungible: MintNonFungibleMethod
"""Constructor-initialized instance of
:class:`MintNonFungibleMethod`.
"""
owner_of: OwnerOfMethod
"""Constructor-initialized instance of
:class:`OwnerOfMethod`.
"""
safe_batch_transfer_from: SafeBatchTransferFromMethod
"""Constructor-initialized instance of
:class:`SafeBatchTransferFromMethod`.
"""
safe_transfer_from: SafeTransferFromMethod
"""Constructor-initialized instance of
:class:`SafeTransferFromMethod`.
"""
set_approval_for_all: SetApprovalForAllMethod
"""Constructor-initialized instance of
:class:`SetApprovalForAllMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: ERC1155MintableValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = ERC1155MintableValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=ERC1155Mintable.abi(),
).functions
self.erc1155_batch_received = Erc1155BatchReceivedMethod(
web3_or_provider,
contract_address,
functions.ERC1155_BATCH_RECEIVED,
)
self.erc1155_received = Erc1155ReceivedMethod(
web3_or_provider, contract_address, functions.ERC1155_RECEIVED
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.balance_of_batch = BalanceOfBatchMethod(
web3_or_provider,
contract_address,
functions.balanceOfBatch,
validator,
)
self.create = CreateMethod(
web3_or_provider, contract_address, functions.create, validator
)
self.create_with_type = CreateWithTypeMethod(
web3_or_provider,
contract_address,
functions.createWithType,
validator,
)
self.creators = CreatorsMethod(
web3_or_provider, contract_address, functions.creators, validator
)
self.get_non_fungible_base_type = GetNonFungibleBaseTypeMethod(
web3_or_provider,
contract_address,
functions.getNonFungibleBaseType,
validator,
)
self.get_non_fungible_index = GetNonFungibleIndexMethod(
web3_or_provider,
contract_address,
functions.getNonFungibleIndex,
validator,
)
self.is_approved_for_all = IsApprovedForAllMethod(
web3_or_provider,
contract_address,
functions.isApprovedForAll,
validator,
)
self.is_fungible = IsFungibleMethod(
web3_or_provider, contract_address, functions.isFungible, validator
)
self.is_non_fungible = IsNonFungibleMethod(
web3_or_provider,
contract_address,
functions.isNonFungible,
validator,
)
self.is_non_fungible_base_type = IsNonFungibleBaseTypeMethod(
web3_or_provider,
contract_address,
functions.isNonFungibleBaseType,
validator,
)
self.is_non_fungible_item = IsNonFungibleItemMethod(
web3_or_provider,
contract_address,
functions.isNonFungibleItem,
validator,
)
self.max_index = MaxIndexMethod(
web3_or_provider, contract_address, functions.maxIndex, validator
)
self.mint_fungible = MintFungibleMethod(
web3_or_provider,
contract_address,
functions.mintFungible,
validator,
)
self.mint_non_fungible = MintNonFungibleMethod(
web3_or_provider,
contract_address,
functions.mintNonFungible,
validator,
)
self.owner_of = OwnerOfMethod(
web3_or_provider, contract_address, functions.ownerOf, validator
)
self.safe_batch_transfer_from = SafeBatchTransferFromMethod(
web3_or_provider,
contract_address,
functions.safeBatchTransferFrom,
validator,
)
self.safe_transfer_from = SafeTransferFromMethod(
web3_or_provider,
contract_address,
functions.safeTransferFrom,
validator,
)
self.set_approval_for_all = SetApprovalForAllMethod(
web3_or_provider,
contract_address,
functions.setApprovalForAll,
validator,
)
def get_approval_for_all_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for ApprovalForAll event.
:param tx_hash: hash of transaction emitting ApprovalForAll event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC1155Mintable.abi(),
)
.events.ApprovalForAll()
.processReceipt(tx_receipt)
)
def get_transfer_batch_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for TransferBatch event.
:param tx_hash: hash of transaction emitting TransferBatch event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC1155Mintable.abi(),
)
.events.TransferBatch()
.processReceipt(tx_receipt)
)
def get_transfer_single_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for TransferSingle event.
:param tx_hash: hash of transaction emitting TransferSingle event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC1155Mintable.abi(),
)
.events.TransferSingle()
.processReceipt(tx_receipt)
)
def get_uri_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for URI event.
:param tx_hash: hash of transaction emitting URI event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=ERC1155Mintable.abi(),
)
.events.URI()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"values","type":"uint256[]"}],"name":"TransferBatch","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"TransferSingle","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"value","type":"string"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"}],"name":"URI","type":"event"},{"constant":true,"inputs":[],"name":"ERC1155_BATCH_RECEIVED","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"ERC1155_RECEIVED","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address[]","name":"owners","type":"address[]"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"}],"name":"balanceOfBatch","outputs":[{"internalType":"uint256[]","name":"balances_","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"string","name":"uri","type":"string"},{"internalType":"bool","name":"isNF","type":"bool"}],"name":"create","outputs":[{"internalType":"uint256","name":"type_","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"type_","type":"uint256"},{"internalType":"string","name":"uri","type":"string"}],"name":"createWithType","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"creators","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"getNonFungibleBaseType","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"getNonFungibleIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"isFungible","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"isNonFungible","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"isNonFungibleBaseType","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"isNonFungibleItem","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"index_0","type":"uint256"}],"name":"maxIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"address[]","name":"to","type":"address[]"},{"internalType":"uint256[]","name":"quantities","type":"uint256[]"}],"name":"mintFungible","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"type_","type":"uint256"},{"internalType":"address[]","name":"to","type":"address[]"}],"name":"mintNonFungible","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"values","type":"uint256[]"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeBatchTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/erc1155_mintable/__init__.py | __init__.py |
"""Generated wrapper for WETH9 Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for WETH9 below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
WETH9Validator,
)
except ImportError:
class WETH9Validator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class NameMethod(ContractMethod):
"""Various interfaces to the name method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class ApproveMethod(ContractMethod):
"""Various interfaces to the approve method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, guy: str, wad: int):
"""Validate the inputs to the approve method."""
self.validator.assert_valid(
method_name="approve", parameter_name="guy", argument_value=guy,
)
guy = self.validate_and_checksum_address(guy)
self.validator.assert_valid(
method_name="approve", parameter_name="wad", argument_value=wad,
)
# safeguard against fractional inputs
wad = int(wad)
return (guy, wad)
def call(
self, guy: str, wad: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(guy, wad) = self.validate_and_normalize_inputs(guy, wad)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(guy, wad).call(tx_params.as_dict())
return bool(returned)
def send_transaction(
self, guy: str, wad: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(guy, wad) = self.validate_and_normalize_inputs(guy, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(guy, wad).transact(tx_params.as_dict())
def build_transaction(
self, guy: str, wad: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(guy, wad) = self.validate_and_normalize_inputs(guy, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(guy, wad).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, guy: str, wad: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(guy, wad) = self.validate_and_normalize_inputs(guy, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(guy, wad).estimateGas(
tx_params.as_dict()
)
class TotalSupplyMethod(ContractMethod):
"""Various interfaces to the totalSupply method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferFromMethod(ContractMethod):
"""Various interfaces to the transferFrom method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, src: str, dst: str, wad: int):
"""Validate the inputs to the transferFrom method."""
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="src",
argument_value=src,
)
src = self.validate_and_checksum_address(src)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="dst",
argument_value=dst,
)
dst = self.validate_and_checksum_address(dst)
self.validator.assert_valid(
method_name="transferFrom",
parameter_name="wad",
argument_value=wad,
)
# safeguard against fractional inputs
wad = int(wad)
return (src, dst, wad)
def call(
self,
src: str,
dst: str,
wad: int,
tx_params: Optional[TxParams] = None,
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(src, dst, wad) = self.validate_and_normalize_inputs(src, dst, wad)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(src, dst, wad).call(
tx_params.as_dict()
)
return bool(returned)
def send_transaction(
self,
src: str,
dst: str,
wad: int,
tx_params: Optional[TxParams] = None,
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(src, dst, wad) = self.validate_and_normalize_inputs(src, dst, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(src, dst, wad).transact(
tx_params.as_dict()
)
def build_transaction(
self,
src: str,
dst: str,
wad: int,
tx_params: Optional[TxParams] = None,
) -> dict:
"""Construct calldata to be used as input to the method."""
(src, dst, wad) = self.validate_and_normalize_inputs(src, dst, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(src, dst, wad).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self,
src: str,
dst: str,
wad: int,
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(src, dst, wad) = self.validate_and_normalize_inputs(src, dst, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(src, dst, wad).estimateGas(
tx_params.as_dict()
)
class WithdrawMethod(ContractMethod):
"""Various interfaces to the withdraw method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, wad: int):
"""Validate the inputs to the withdraw method."""
self.validator.assert_valid(
method_name="withdraw", parameter_name="wad", argument_value=wad,
)
# safeguard against fractional inputs
wad = int(wad)
return wad
def call(self, wad: int, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(wad) = self.validate_and_normalize_inputs(wad)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(wad).call(tx_params.as_dict())
def send_transaction(
self, wad: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(wad) = self.validate_and_normalize_inputs(wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(wad).transact(tx_params.as_dict())
def build_transaction(
self, wad: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(wad) = self.validate_and_normalize_inputs(wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(wad).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, wad: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(wad) = self.validate_and_normalize_inputs(wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(wad).estimateGas(tx_params.as_dict())
class DecimalsMethod(ContractMethod):
"""Various interfaces to the decimals method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return int(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class BalanceOfMethod(ContractMethod):
"""Various interfaces to the balanceOf method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str):
"""Validate the inputs to the balanceOf method."""
self.validator.assert_valid(
method_name="balanceOf",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
return index_0
def call(self, index_0: str, tx_params: Optional[TxParams] = None) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0).call(tx_params.as_dict())
return int(returned)
def estimate_gas(
self, index_0: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0) = self.validate_and_normalize_inputs(index_0)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0).estimateGas(
tx_params.as_dict()
)
class SymbolMethod(ContractMethod):
"""Various interfaces to the symbol method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> str:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method().call(tx_params.as_dict())
return str(returned)
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class TransferMethod(ContractMethod):
"""Various interfaces to the transfer method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, dst: str, wad: int):
"""Validate the inputs to the transfer method."""
self.validator.assert_valid(
method_name="transfer", parameter_name="dst", argument_value=dst,
)
dst = self.validate_and_checksum_address(dst)
self.validator.assert_valid(
method_name="transfer", parameter_name="wad", argument_value=wad,
)
# safeguard against fractional inputs
wad = int(wad)
return (dst, wad)
def call(
self, dst: str, wad: int, tx_params: Optional[TxParams] = None
) -> bool:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(dst, wad) = self.validate_and_normalize_inputs(dst, wad)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(dst, wad).call(tx_params.as_dict())
return bool(returned)
def send_transaction(
self, dst: str, wad: int, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
(dst, wad) = self.validate_and_normalize_inputs(dst, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(dst, wad).transact(tx_params.as_dict())
def build_transaction(
self, dst: str, wad: int, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(dst, wad) = self.validate_and_normalize_inputs(dst, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(dst, wad).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, dst: str, wad: int, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(dst, wad) = self.validate_and_normalize_inputs(dst, wad)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(dst, wad).estimateGas(
tx_params.as_dict()
)
class DepositMethod(ContractMethod):
"""Various interfaces to the deposit method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address)
self._underlying_method = contract_function
def call(self, tx_params: Optional[TxParams] = None) -> None:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method().call(tx_params.as_dict())
def send_transaction(
self, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
:param tx_params: transaction parameters
"""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().transact(tx_params.as_dict())
def build_transaction(self, tx_params: Optional[TxParams] = None) -> dict:
"""Construct calldata to be used as input to the method."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().buildTransaction(tx_params.as_dict())
def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
"""Estimate gas consumption of method call."""
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method().estimateGas(tx_params.as_dict())
class AllowanceMethod(ContractMethod):
"""Various interfaces to the allowance method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, index_0: str, index_1: str):
"""Validate the inputs to the allowance method."""
self.validator.assert_valid(
method_name="allowance",
parameter_name="index_0",
argument_value=index_0,
)
index_0 = self.validate_and_checksum_address(index_0)
self.validator.assert_valid(
method_name="allowance",
parameter_name="index_1",
argument_value=index_1,
)
index_1 = self.validate_and_checksum_address(index_1)
return (index_0, index_1)
def call(
self, index_0: str, index_1: str, tx_params: Optional[TxParams] = None
) -> int:
"""Execute underlying contract method via eth_call.
:param tx_params: transaction parameters
"""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(index_0, index_1).call(
tx_params.as_dict()
)
return int(returned)
def estimate_gas(
self, index_0: str, index_1: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(index_0, index_1) = self.validate_and_normalize_inputs(
index_0, index_1
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(index_0, index_1).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class WETH9:
"""Wrapper class for WETH9 Solidity contract."""
name: NameMethod
"""Constructor-initialized instance of
:class:`NameMethod`.
"""
approve: ApproveMethod
"""Constructor-initialized instance of
:class:`ApproveMethod`.
"""
total_supply: TotalSupplyMethod
"""Constructor-initialized instance of
:class:`TotalSupplyMethod`.
"""
transfer_from: TransferFromMethod
"""Constructor-initialized instance of
:class:`TransferFromMethod`.
"""
withdraw: WithdrawMethod
"""Constructor-initialized instance of
:class:`WithdrawMethod`.
"""
decimals: DecimalsMethod
"""Constructor-initialized instance of
:class:`DecimalsMethod`.
"""
balance_of: BalanceOfMethod
"""Constructor-initialized instance of
:class:`BalanceOfMethod`.
"""
symbol: SymbolMethod
"""Constructor-initialized instance of
:class:`SymbolMethod`.
"""
transfer: TransferMethod
"""Constructor-initialized instance of
:class:`TransferMethod`.
"""
deposit: DepositMethod
"""Constructor-initialized instance of
:class:`DepositMethod`.
"""
allowance: AllowanceMethod
"""Constructor-initialized instance of
:class:`AllowanceMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: WETH9Validator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = WETH9Validator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=WETH9.abi()
).functions
self.name = NameMethod(
web3_or_provider, contract_address, functions.name
)
self.approve = ApproveMethod(
web3_or_provider, contract_address, functions.approve, validator
)
self.total_supply = TotalSupplyMethod(
web3_or_provider, contract_address, functions.totalSupply
)
self.transfer_from = TransferFromMethod(
web3_or_provider,
contract_address,
functions.transferFrom,
validator,
)
self.withdraw = WithdrawMethod(
web3_or_provider, contract_address, functions.withdraw, validator
)
self.decimals = DecimalsMethod(
web3_or_provider, contract_address, functions.decimals
)
self.balance_of = BalanceOfMethod(
web3_or_provider, contract_address, functions.balanceOf, validator
)
self.symbol = SymbolMethod(
web3_or_provider, contract_address, functions.symbol
)
self.transfer = TransferMethod(
web3_or_provider, contract_address, functions.transfer, validator
)
self.deposit = DepositMethod(
web3_or_provider, contract_address, functions.deposit
)
self.allowance = AllowanceMethod(
web3_or_provider, contract_address, functions.allowance, validator
)
def get_approval_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Approval event.
:param tx_hash: hash of transaction emitting Approval event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=WETH9.abi(),
)
.events.Approval()
.processReceipt(tx_receipt)
)
def get_transfer_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Transfer event.
:param tx_hash: hash of transaction emitting Transfer event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=WETH9.abi(),
)
.events.Transfer()
.processReceipt(tx_receipt)
)
def get_deposit_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Deposit event.
:param tx_hash: hash of transaction emitting Deposit event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=WETH9.abi(),
)
.events.Deposit()
.processReceipt(tx_receipt)
)
def get_withdrawal_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for Withdrawal event.
:param tx_hash: hash of transaction emitting Withdrawal event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=WETH9.abi(),
)
.events.Withdrawal()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"wad","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"index_0","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"name":"index_0","type":"address"},{"name":"index_1","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Withdrawal","type":"event"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/weth9/__init__.py | __init__.py |
"""Generated wrapper for IWallet Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for IWallet below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
IWalletValidator,
)
except ImportError:
class IWalletValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class IsValidSignatureMethod(ContractMethod):
"""Various interfaces to the isValidSignature method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(
self, _hash: Union[bytes, str], signature: Union[bytes, str]
):
"""Validate the inputs to the isValidSignature method."""
self.validator.assert_valid(
method_name="isValidSignature",
parameter_name="hash",
argument_value=_hash,
)
self.validator.assert_valid(
method_name="isValidSignature",
parameter_name="signature",
argument_value=signature,
)
return (_hash, signature)
def call(
self,
_hash: Union[bytes, str],
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> Union[bytes, str]:
"""Execute underlying contract method via eth_call.
Validates a hash with the `Wallet` signature type.
:param hash: Message hash that is signed.
:param signature: Proof of signing.
:param tx_params: transaction parameters
:returns: magicValue `bytes4(0xb0671381)` if the signature check
succeeds.
"""
(_hash, signature) = self.validate_and_normalize_inputs(
_hash, signature
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(_hash, signature).call(
tx_params.as_dict()
)
return Union[bytes, str](returned)
def estimate_gas(
self,
_hash: Union[bytes, str],
signature: Union[bytes, str],
tx_params: Optional[TxParams] = None,
) -> int:
"""Estimate gas consumption of method call."""
(_hash, signature) = self.validate_and_normalize_inputs(
_hash, signature
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(_hash, signature).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class IWallet:
"""Wrapper class for IWallet Solidity contract.
All method parameters of type `bytes`:code: should be encoded as UTF-8,
which can be accomplished via `str.encode("utf_8")`:code:.
"""
is_valid_signature: IsValidSignatureMethod
"""Constructor-initialized instance of
:class:`IsValidSignatureMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: IWalletValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = IWalletValidator(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address), abi=IWallet.abi()
).functions
self.is_valid_signature = IsValidSignatureMethod(
web3_or_provider,
contract_address,
functions.isValidSignature,
validator,
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"constant":true,"inputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"isValidSignature","outputs":[{"internalType":"bytes4","name":"magicValue","type":"bytes4"}],"payable":false,"stateMutability":"view","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/i_wallet/__init__.py | __init__.py |
"""Generated wrapper for CoordinatorRegistry Solidity contract."""
# pylint: disable=too-many-arguments
import json
from typing import ( # pylint: disable=unused-import
Any,
List,
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from zero_ex.contract_wrappers.bases import ContractMethod, Validator
from zero_ex.contract_wrappers.tx_params import TxParams
# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for CoordinatorRegistry below.
try:
# both mypy and pylint complain about what we're doing here, but this
# works just fine, so their messages have been disabled here.
from . import ( # type: ignore # pylint: disable=import-self
CoordinatorRegistryValidator,
)
except ImportError:
class CoordinatorRegistryValidator( # type: ignore
Validator
):
"""No-op input validator."""
try:
from .middleware import MIDDLEWARE # type: ignore
except ImportError:
pass
class GetCoordinatorEndpointMethod(ContractMethod):
"""Various interfaces to the getCoordinatorEndpoint method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, coordinator_operator: str):
"""Validate the inputs to the getCoordinatorEndpoint method."""
self.validator.assert_valid(
method_name="getCoordinatorEndpoint",
parameter_name="coordinatorOperator",
argument_value=coordinator_operator,
)
coordinator_operator = self.validate_and_checksum_address(
coordinator_operator
)
return coordinator_operator
def call(
self, coordinator_operator: str, tx_params: Optional[TxParams] = None
) -> str:
"""Execute underlying contract method via eth_call.
Gets the endpoint for a Coordinator.
:param coordinatorOperator: Operator of the Coordinator endpoint.
:param tx_params: transaction parameters
:returns: coordinatorEndpoint Endpoint of the Coordinator as a string.
"""
(coordinator_operator) = self.validate_and_normalize_inputs(
coordinator_operator
)
tx_params = super().normalize_tx_params(tx_params)
returned = self._underlying_method(coordinator_operator).call(
tx_params.as_dict()
)
return str(returned)
def estimate_gas(
self, coordinator_operator: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(coordinator_operator) = self.validate_and_normalize_inputs(
coordinator_operator
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(coordinator_operator).estimateGas(
tx_params.as_dict()
)
class SetCoordinatorEndpointMethod(ContractMethod):
"""Various interfaces to the setCoordinatorEndpoint method."""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
contract_function: ContractFunction,
validator: Validator = None,
):
"""Persist instance data."""
super().__init__(web3_or_provider, contract_address, validator)
self._underlying_method = contract_function
def validate_and_normalize_inputs(self, coordinator_endpoint: str):
"""Validate the inputs to the setCoordinatorEndpoint method."""
self.validator.assert_valid(
method_name="setCoordinatorEndpoint",
parameter_name="coordinatorEndpoint",
argument_value=coordinator_endpoint,
)
return coordinator_endpoint
def call(
self, coordinator_endpoint: str, tx_params: Optional[TxParams] = None
) -> None:
"""Execute underlying contract method via eth_call.
Called by a Coordinator operator to set the endpoint of their
Coordinator.
:param coordinatorEndpoint: Endpoint of the Coordinator as a string.
:param tx_params: transaction parameters
:returns: the return value of the underlying method.
"""
(coordinator_endpoint) = self.validate_and_normalize_inputs(
coordinator_endpoint
)
tx_params = super().normalize_tx_params(tx_params)
self._underlying_method(coordinator_endpoint).call(tx_params.as_dict())
def send_transaction(
self, coordinator_endpoint: str, tx_params: Optional[TxParams] = None
) -> Union[HexBytes, bytes]:
"""Execute underlying contract method via eth_sendTransaction.
Called by a Coordinator operator to set the endpoint of their
Coordinator.
:param coordinatorEndpoint: Endpoint of the Coordinator as a string.
:param tx_params: transaction parameters
"""
(coordinator_endpoint) = self.validate_and_normalize_inputs(
coordinator_endpoint
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(coordinator_endpoint).transact(
tx_params.as_dict()
)
def build_transaction(
self, coordinator_endpoint: str, tx_params: Optional[TxParams] = None
) -> dict:
"""Construct calldata to be used as input to the method."""
(coordinator_endpoint) = self.validate_and_normalize_inputs(
coordinator_endpoint
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(coordinator_endpoint).buildTransaction(
tx_params.as_dict()
)
def estimate_gas(
self, coordinator_endpoint: str, tx_params: Optional[TxParams] = None
) -> int:
"""Estimate gas consumption of method call."""
(coordinator_endpoint) = self.validate_and_normalize_inputs(
coordinator_endpoint
)
tx_params = super().normalize_tx_params(tx_params)
return self._underlying_method(coordinator_endpoint).estimateGas(
tx_params.as_dict()
)
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class CoordinatorRegistry:
"""Wrapper class for CoordinatorRegistry Solidity contract."""
get_coordinator_endpoint: GetCoordinatorEndpointMethod
"""Constructor-initialized instance of
:class:`GetCoordinatorEndpointMethod`.
"""
set_coordinator_endpoint: SetCoordinatorEndpointMethod
"""Constructor-initialized instance of
:class:`SetCoordinatorEndpointMethod`.
"""
def __init__(
self,
web3_or_provider: Union[Web3, BaseProvider],
contract_address: str,
validator: CoordinatorRegistryValidator = None,
):
"""Get an instance of wrapper for smart contract.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param contract_address: where the contract has been deployed
:param validator: for validation of method inputs.
"""
# pylint: disable=too-many-statements
self.contract_address = contract_address
if not validator:
validator = CoordinatorRegistryValidator(
web3_or_provider, contract_address
)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
# if any middleware was imported, inject it
try:
MIDDLEWARE
except NameError:
pass
else:
try:
for middleware in MIDDLEWARE:
web3.middleware_onion.inject(
middleware["function"], layer=middleware["layer"],
)
except ValueError as value_error:
if value_error.args == (
"You can't add the same un-named instance twice",
):
pass
self._web3_eth = web3.eth
functions = self._web3_eth.contract(
address=to_checksum_address(contract_address),
abi=CoordinatorRegistry.abi(),
).functions
self.get_coordinator_endpoint = GetCoordinatorEndpointMethod(
web3_or_provider,
contract_address,
functions.getCoordinatorEndpoint,
validator,
)
self.set_coordinator_endpoint = SetCoordinatorEndpointMethod(
web3_or_provider,
contract_address,
functions.setCoordinatorEndpoint,
validator,
)
def get_coordinator_endpoint_set_event(
self, tx_hash: Union[HexBytes, bytes]
) -> Tuple[AttributeDict]:
"""Get log entry for CoordinatorEndpointSet event.
:param tx_hash: hash of transaction emitting CoordinatorEndpointSet
event
"""
tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash)
return (
self._web3_eth.contract(
address=to_checksum_address(self.contract_address),
abi=CoordinatorRegistry.abi(),
)
.events.CoordinatorEndpointSet()
.processReceipt(tx_receipt)
)
@staticmethod
def abi():
"""Return the ABI to the underlying contract."""
return json.loads(
'[{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"coordinatorOperator","type":"address"},{"indexed":false,"internalType":"string","name":"coordinatorEndpoint","type":"string"}],"name":"CoordinatorEndpointSet","type":"event"},{"constant":true,"inputs":[{"internalType":"address","name":"coordinatorOperator","type":"address"}],"name":"getCoordinatorEndpoint","outputs":[{"internalType":"string","name":"coordinatorEndpoint","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"string","name":"coordinatorEndpoint","type":"string"}],"name":"setCoordinatorEndpoint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]' # noqa: E501 (line-too-long)
)
# pylint: disable=too-many-lines
| 0x-contract-wrappers | /0x_contract_wrappers-2.0.0-py3-none-any.whl/zero_ex/contract_wrappers/coordinator_registry/__init__.py | __init__.py |
"""0x JSON schemas and associated utilities.
Setup
-----
Install the package with pip::
pip install 0x-json-schemas
"""
from os import path
import json
from typing import Mapping
from pkg_resources import resource_string
import jsonschema
from stringcase import snakecase
class _LocalRefResolver(jsonschema.RefResolver):
"""Resolve package-local JSON schema id's."""
def __init__(self):
"""Initialize a new instance."""
jsonschema.RefResolver.__init__(self, "", "")
@staticmethod
def resolve_from_url(url: str) -> str:
"""Resolve the given URL.
:param url: a string representing the URL of the JSON schema to fetch.
:returns: a string representing the deserialized JSON schema
:raises jsonschema.ValidationError: when the resource associated with
`url` does not exist.
"""
ref = url.replace("file://", "")
return json.loads(
resource_string(
"zero_ex.json_schemas",
f"schemas/{snakecase(ref.lstrip('/'))}.json",
)
)
# Instantiate the `_LocalRefResolver()` only once so that `assert_valid()` can
# perform multiple schema validations without reading from disk the schema
# every time.
_LOCAL_RESOLVER = _LocalRefResolver()
def assert_valid(data: Mapping, schema_id: str) -> None:
"""Validate the given `data` against the specified `schema`.
:param data: Python dictionary to be validated as a JSON object.
:param schema_id: id property of the JSON schema to validate against. Must
be one of those listed in `the 0x JSON schema files
<https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas/schemas>`_.
Raises an exception if validation fails.
>>> from zero_ex.json_schemas import assert_valid
>>> from zero_ex.contract_addresses import chain_to_addresses, ChainId
>>> from eth_utils import remove_0x_prefix
>>> import random
>>> from datetime import datetime, timedelta
>>> assert_valid(
... {'makerAddress': '0x5409ed021d9299bf6814279a6a1411a7e866a631',
... 'takerAddress': '0x0000000000000000000000000000000000000000',
... 'senderAddress': '0x0000000000000000000000000000000000000000',
... 'exchangeAddress': '0x4f833a24e1f95d70f028921e27040ca56e09ab0b',
... 'feeRecipientAddress': (
... '0x0000000000000000000000000000000000000000'
... ),
... 'makerAssetData': (
... chain_to_addresses(ChainId.MAINNET).zrx_token
... ),
... 'takerAssetData': (
... chain_to_addresses(ChainId.MAINNET).ether_token
... ),
... 'salt': random.randint(1, 100000000000000000),
... 'makerFee': 0,
... 'makerFeeAssetData': '0x' + '00'*20,
... 'takerFee': 0,
... 'takerFeeAssetData': '0x' + '00'*20,
... 'makerAssetAmount': 1000000000000000000,
... 'takerAssetAmount': 500000000000000000000,
... 'expirationTimeSeconds': round(
... (datetime.utcnow() + timedelta(days=1)).timestamp()
... ),
... 'chainId': 50
... },
... "/orderSchema"
... )
"""
_, schema = _LOCAL_RESOLVER.resolve(schema_id)
jsonschema.validate(data, schema, resolver=_LOCAL_RESOLVER)
def assert_valid_json(data: str, schema_id: str) -> None:
"""Validate the given `data` against the specified `schema`.
:param data: JSON string to be validated.
:param schema_id: id property of the JSON schema to validate against. Must
be one of those listed in `the 0x JSON schema files
<https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas/schemas>`_.
Raises an exception if validation fails.
>>> assert_valid_json(
... '''{
... "v": 27,
... "r": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
... "s": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
... }''',
... '/ecSignatureSchema',
... )
""" # noqa: E501 (line too long)
assert_valid(json.loads(data), schema_id)
| 0x-json-schemas | /0x_json_schemas-2.1.0-py3-none-any.whl/zero_ex/json_schemas/__init__.py | __init__.py |
"""Middleware that captures all 'eth_sign' requests to the JSON-RPC-Server.
An adaptation of the signing middleware from `web3.py
<https://github.com/ethereum/web3.py/blob/master/web3/middleware/signing.py>`_.
This middleware intercepts all 'eth_sign' requests to
an ethereum JSON RPC-Server and signs messages with a local private key.
"""
from functools import singledispatch
from typing import Dict, List, Set, Tuple, Union
from eth_account import Account, messages
from eth_account.signers.local import LocalAccount
from eth_keys.datatypes import PrivateKey
from hexbytes import HexBytes
@singledispatch
def _to_account(private_key_or_account):
"""Get a `LocalAccount` instance from a private_key or a `LocalAccount`.
Note that this function is overloaded based on the type on input. This
implementation is the base case where none of the supported types are
matched and we throw an exception.
"""
raise TypeError(
"key must be one of the types:"
"eth_keys.datatype.PrivateKey, "
"eth_account.local.LocalAccount, "
"or raw private key as a hex string or byte string. "
"Was of type {0}".format(type(private_key_or_account))
)
def _private_key_to_account(private_key):
"""Get the account associated with the private key."""
if isinstance(private_key, PrivateKey):
private_key = private_key.to_hex()
else:
private_key = HexBytes(private_key).hex()
return Account().privateKeyToAccount(private_key)
_to_account.register(LocalAccount, lambda x: x)
_to_account.register(PrivateKey, _private_key_to_account)
_to_account.register(str, _private_key_to_account)
_to_account.register(bytes, _private_key_to_account)
def construct_local_message_signer(
private_key_or_account: Union[
Union[LocalAccount, PrivateKey, str],
List[Union[LocalAccount, PrivateKey, str]],
Tuple[Union[LocalAccount, PrivateKey, str]],
Set[Union[LocalAccount, PrivateKey, str]],
]
):
"""Construct a local messager signer middleware.
:param private_key_or_account: a single private key or a tuple,
list, or set of private keys. Keys can be any of the following
formats:
- An `eth_account.LocalAccount`:code: object
- An `eth_keys.PrivateKey`:code: object
- A raw private key as a hex `string`:code: or as `bytes`:code:
:returns: callable local_message_signer_middleware
>>> private_key=(
... "f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d"
... )
>>> from web3 import Web3, HTTPProvider
>>> Web3(
... HTTPProvider("https://mainnet.infura.io/v3/API_KEY")
... ).middleware_onion.add(
... construct_local_message_signer(private_key)
... )
"""
if not isinstance(private_key_or_account, (list, tuple, set)):
private_key_or_account = [private_key_or_account]
accounts = [_to_account(pkoa) for pkoa in private_key_or_account]
address_to_accounts: Dict[str, LocalAccount] = {
account.address: account for account in accounts
}
def local_message_signer_middleware(
make_request, web3
): # pylint: disable=unused-argument
def middleware(method, params):
if method != "eth_sign":
return make_request(method, params)
account_address, message = params[:2]
account = address_to_accounts[account_address]
# We will assume any string which looks like a hex is expected
# to be converted to hex. Non-hexable strings are forcibly
# converted by encoding them to utf-8
try:
message = HexBytes(message)
except Exception: # pylint: disable=broad-except
message = HexBytes(message.encode("utf-8"))
msg_hash_hexbytes = messages.defunct_hash_message(message)
ec_signature = account.signHash(msg_hash_hexbytes)
return {"result": ec_signature.signature}
return middleware
return local_message_signer_middleware
| 0x-middlewares | /0x_middlewares-1.0.0-py3-none-any.whl/zero_ex/middlewares/local_message_signer.py | local_message_signer.py |
"""Web3 middlewares for 0x applications.
Setup
-----
Install the package with pip::
pip install 0x-middlewares
"""
| 0x-middlewares | /0x_middlewares-1.0.0-py3-none-any.whl/zero_ex/middlewares/__init__.py | __init__.py |
"""Ethereum ABI utilities.
Builds on the eth-abi package, adding some convenience methods like those found
in npmjs.com/package/ethereumjs-abi. Ideally, all of this code should be
pushed upstream into eth-abi.
"""
import re
from typing import Any, List
from mypy_extensions import TypedDict
from eth_abi import encode_abi
from web3 import Web3
from .type_assertions import assert_is_string, assert_is_list
class MethodSignature(TypedDict, total=False):
"""Object interface to an ABI method signature."""
method: str
args: List[str]
def parse_signature(signature: str) -> MethodSignature:
"""Parse a method signature into its constituent parts.
>>> parse_signature("ERC20Token(address)")
{'method': 'ERC20Token', 'args': ['address']}
"""
assert_is_string(signature, "signature")
matches = re.match(r"^(\w+)\((.+)\)$", signature)
if matches is None:
raise ValueError(f"Invalid method signature {signature}")
return {"method": matches[1], "args": matches[2].split(",")}
def elementary_name(name: str) -> str:
"""Convert from short to canonical names; barely implemented.
Modeled after ethereumjs-abi's ABI.elementaryName(), but only implemented
to support our particular use case and a few other simple ones.
>>> elementary_name("address")
'address'
>>> elementary_name("uint")
'uint256'
"""
assert_is_string(name, "name")
return {
"int": "int256",
"uint": "uint256",
"fixed": "fixed128x128",
"ufixed": "ufixed128x128",
}.get(name, name)
def event_id(name: str, types: List[str]) -> str:
"""Return the Keccak-256 hash of the given method.
>>> event_id("ERC20Token", ["address"])
'0xf47261b06eedbfce68afd46d0f3c27c60b03faad319eaf33103611cf8f6456ad'
"""
assert_is_string(name, "name")
assert_is_list(types, "types")
signature = f"{name}({','.join(list(map(elementary_name, types)))})"
return Web3.sha3(text=signature).hex()
def method_id(name: str, types: List[str]) -> str:
"""Return the 4-byte method identifier.
>>> method_id("ERC20Token", ["address"])
'0xf47261b0'
"""
assert_is_string(name, "name")
assert_is_list(types, "types")
return event_id(name, types)[0:10]
def simple_encode(method: str, *args: Any) -> bytes:
r"""Encode a method ABI.
>>> simple_encode("ERC20Token(address)", "0x1dc4c1cefef38a777b15aa20260a54e584b16c48")
b'\xf4ra\xb0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1d\xc4\xc1\xce\xfe\xf3\x8aw{\x15\xaa &\nT\xe5\x84\xb1lH'
""" # noqa: E501 (line too long)
assert_is_string(method, "method")
signature: MethodSignature = parse_signature(method)
return bytes.fromhex(
(
method_id(signature["method"], signature["args"])
+ encode_abi(signature["args"], args).hex()
)[2:]
)
| 0x-order-utils | /0x_order_utils-4.0.1-py3-none-any.whl/zero_ex/dev_utils/abi_utils.py | abi_utils.py |
"""Assertions for runtime type checking of function arguments."""
from typing import Any
from eth_utils import is_address
from web3.providers.base import BaseProvider
def assert_is_string(value: Any, name: str) -> None:
"""If :param value: isn't of type str, raise a TypeError.
>>> try: assert_is_string(123, 'var')
... except TypeError as type_error: print(str(type_error))
...
expected variable 'var', with value 123, to have type 'str', not 'int'
"""
if not isinstance(value, str):
raise TypeError(
f"expected variable '{name}', with value {str(value)}, to have"
+ f" type 'str', not '{type(value).__name__}'"
)
def assert_is_list(value: Any, name: str) -> None:
"""If :param value: isn't of type list, raise a TypeError.
>>> try: assert_is_list(123, 'var')
... except TypeError as type_error: print(str(type_error))
...
expected variable 'var', with value 123, to have type 'list', not 'int'
"""
if not isinstance(value, list):
raise TypeError(
f"expected variable '{name}', with value {str(value)}, to have"
+ f" type 'list', not '{type(value).__name__}'"
)
def assert_is_int(value: Any, name: str) -> None:
"""If :param value: isn't of type int, raise a TypeError.
>>> try: assert_is_int('asdf', 'var')
... except TypeError as type_error: print(str(type_error))
...
expected variable 'var', with value asdf, to have type 'int', not 'str'
"""
if not isinstance(value, int):
raise TypeError(
f"expected variable '{name}', with value {str(value)}, to have"
+ f" type 'int', not '{type(value).__name__}'"
)
def assert_is_hex_string(value: Any, name: str) -> None:
"""Assert that :param value: is a string of hex chars.
If :param value: isn't a str, raise a TypeError. If it is a string but
contains non-hex characters ("0x" prefix permitted), raise a ValueError.
"""
assert_is_string(value, name)
int(value, 16) # raises a ValueError if value isn't a base-16 str
def assert_is_address(value: Any, name: str) -> None:
"""Assert that `value` is a valid Ethereum address.
If `value` isn't a hex string, raise a TypeError. If it isn't a valid
Ethereum address, raise a ValueError.
"""
assert_is_hex_string(value, name)
if not is_address(value):
raise ValueError(
f"Expected variable '{name}' to be a valid Ethereum"
+ " address, but it's not."
)
def assert_is_provider(value: Any, name: str) -> None:
"""Assert that `value` is a Web3 provider.
If `value` isn't a Web3 provider, raise a TypeError.
"""
if not isinstance(value, BaseProvider):
raise TypeError(
f"Expected variable '{name}' to be an instance of a Web3 provider,"
+ " but it's not."
)
| 0x-order-utils | /0x_order_utils-4.0.1-py3-none-any.whl/zero_ex/dev_utils/type_assertions.py | type_assertions.py |
"""Dev utils to be shared across 0x projects and packages."""
| 0x-order-utils | /0x_order_utils-4.0.1-py3-none-any.whl/zero_ex/dev_utils/__init__.py | __init__.py |
"""Asset data encoding and decoding utilities."""
from typing import NamedTuple
import eth_abi
from deprecated.sphinx import deprecated
from zero_ex.dev_utils import abi_utils
from zero_ex.dev_utils.type_assertions import assert_is_string, assert_is_int
ERC20_ASSET_DATA_BYTE_LENGTH = 36
ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH = 53
SELECTOR_LENGTH = 10
class ERC20AssetData(NamedTuple):
"""Object interface to ERC20 asset data."""
asset_proxy_id: str
"""Asset proxy identifier."""
token_address: str
"""Token address"""
class ERC721AssetData(NamedTuple):
"""Object interface to ERC721 asset data."""
asset_proxy_id: str
"""Asset proxy identifier."""
token_address: str
"""Token address"""
token_id: int
"""Token identifier."""
@deprecated(reason='use `"0x"+encode_erc20().hex()` instead', version="4.0.0")
def encode_erc20_asset_data(token_address: str) -> str:
"""Encode an ERC20 token address into an asset data string.
:param token_address: the ERC20 token's contract address.
:returns: hex encoded asset data string, usable in the makerAssetData or
takerAssetData fields in a 0x order.
>>> encode_erc20_asset_data('0x1dc4c1cefef38a777b15aa20260a54e584b16c48')
'0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48'
"""
assert_is_string(token_address, "token_address")
return (
"0x"
+ abi_utils.simple_encode("ERC20Token(address)", token_address).hex()
)
def encode_erc20(token_address: str) -> bytes:
"""Encode an ERC20 token address into asset data bytes.
:param token_address: the ERC20 token's contract address.
:returns: hex encoded asset data string, usable in the makerAssetData or
takerAssetData fields in a 0x order.
>>> encode_erc20('0x1dc4c1cefef38a777b15aa20260a54e584b16c48').hex()
'f47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48'
"""
assert_is_string(token_address, "token_address")
return abi_utils.simple_encode("ERC20Token(address)", token_address)
def decode_erc20_asset_data(asset_data: str) -> ERC20AssetData:
"""Decode an ERC20 asset data hex string.
:param asset_data: String produced by prior call to encode_erc20_asset_data()
>>> decode_erc20_asset_data("0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48")
ERC20AssetData(asset_proxy_id='0xf47261b0', token_address='0x1dc4c1cefef38a777b15aa20260a54e584b16c48')
""" # noqa: E501 (line too long)
assert_is_string(asset_data, "asset_data")
if len(asset_data) < ERC20_ASSET_DATA_BYTE_LENGTH:
raise ValueError(
"Could not decode ERC20 Proxy Data. Expected length of encoded"
+ f" data to be at least {str(ERC20_ASSET_DATA_BYTE_LENGTH)}."
+ f" Got {str(len(asset_data))}."
)
asset_proxy_id: str = asset_data[0:SELECTOR_LENGTH]
if asset_proxy_id != abi_utils.method_id("ERC20Token", ["address"]):
raise ValueError(
"Could not decode ERC20 Proxy Data. Expected Asset Proxy Id to be"
+ f" ERC20 ({abi_utils.method_id('ERC20Token', ['address'])})"
+ f" but got {asset_proxy_id}."
)
# workaround for https://github.com/PyCQA/pylint/issues/1498
# pylint: disable=unsubscriptable-object
token_address = eth_abi.decode_abi(
["address"], bytes.fromhex(asset_data[SELECTOR_LENGTH:])
)[0]
return ERC20AssetData(
asset_proxy_id=asset_proxy_id, token_address=token_address
)
@deprecated(reason='use `"0x"+encode_erc721().hex()` instead', version="4.0.0")
def encode_erc721_asset_data(token_address: str, token_id: int) -> str:
"""Encode an ERC721 asset data hex string.
:param token_address: the ERC721 token's contract address.
:param token_id: the identifier of the asset's instance of the token.
:returns: hex encoded asset data string, usable in the makerAssetData or
takerAssetData fields in a 0x order.
>>> encode_erc721_asset_data('0x1dc4c1cefef38a777b15aa20260a54e584b16c48', 1)
'0x025717920000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c480000000000000000000000000000000000000000000000000000000000000001'
""" # noqa: E501 (line too long)
assert_is_string(token_address, "token_address")
assert_is_int(token_id, "token_id")
return (
"0x"
+ abi_utils.simple_encode(
"ERC721Token(address,uint256)", token_address, token_id
).hex()
)
def encode_erc721(token_address: str, token_id: int) -> bytes:
"""Encode an ERC721 token address into asset data bytes.
:param token_address: the ERC721 token's contract address.
:param token_id: the identifier of the asset's instance of the token.
:returns: hex encoded asset data string, usable in the makerAssetData or
takerAssetData fields in a 0x order.
>>> encode_erc721('0x1dc4c1cefef38a777b15aa20260a54e584b16c48', 1).hex()
'025717920000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c480000000000000000000000000000000000000000000000000000000000000001'
""" # noqa: E501 (line too long)
assert_is_string(token_address, "token_address")
assert_is_int(token_id, "token_id")
return abi_utils.simple_encode(
"ERC721Token(address,uint256)", token_address, token_id
)
def decode_erc721_asset_data(asset_data: str) -> ERC721AssetData:
"""Decode an ERC721 asset data hex string.
>>> decode_erc721_asset_data('0x025717920000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c480000000000000000000000000000000000000000000000000000000000000001')
ERC721AssetData(asset_proxy_id='0x02571792', token_address='0x1dc4c1cefef38a777b15aa20260a54e584b16c48', token_id=1)
""" # noqa: E501 (line too long)
assert_is_string(asset_data, "asset_data")
if len(asset_data) < ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH:
raise ValueError(
"Could not decode ERC721 Asset Data. Expected length of encoded"
+ f"data to be at least {ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH}. "
+ f"Got {len(asset_data)}."
)
asset_proxy_id: str = asset_data[0:SELECTOR_LENGTH]
if asset_proxy_id != abi_utils.method_id(
"ERC721Token", ["address", "uint256"]
):
raise ValueError(
"Could not decode ERC721 Asset Data. Expected Asset Proxy Id to be"
+ " ERC721 ("
+ f"{abi_utils.method_id('ERC721Token', ['address', 'uint256'])}"
+ f"), but got {asset_proxy_id}"
)
(token_address, token_id) = eth_abi.decode_abi(
["address", "uint256"], bytes.fromhex(asset_data[SELECTOR_LENGTH:])
)
return ERC721AssetData(
asset_proxy_id=asset_proxy_id,
token_address=token_address,
token_id=token_id,
)
| 0x-order-utils | /0x_order_utils-4.0.1-py3-none-any.whl/zero_ex/order_utils/asset_data_utils.py | asset_data_utils.py |
r"""Order utilities for 0x applications.
Setup
-----
Install the package with pip::
pip install 0x-order-utils
Some methods require the caller to pass in a `Web3.BaseProvider`:code: object.
For local testing one may construct such a provider pointing at an instance of
`ganache-cli <https://www.npmjs.com/package/ganache-cli>`_ which has the 0x
contracts deployed on it. For convenience, a docker container is provided for
just this purpose. To start it::
docker run -d -p 8545:8545 0xorg/ganache-cli
"""
from enum import auto, Enum
import json
from typing import cast, Tuple, Union
from pkg_resources import resource_string
from mypy_extensions import TypedDict
from eth_typing import HexStr
from eth_utils import keccak, remove_0x_prefix, to_bytes, to_checksum_address
from web3 import Web3
import web3.exceptions
from web3.providers.base import BaseProvider
from web3.contract import Contract
from zero_ex.contract_addresses import chain_to_addresses, ChainId
import zero_ex.contract_artifacts
from zero_ex.contract_wrappers.exchange import Exchange
from zero_ex.contract_wrappers.exchange.types import Order
from zero_ex.contract_wrappers.order_conversions import order_to_jsdict
from zero_ex.dev_utils.type_assertions import (
assert_is_address,
assert_is_hex_string,
assert_is_provider,
)
from zero_ex.json_schemas import assert_valid
class _Constants:
"""Static data used by order utilities."""
null_address = "0x0000000000000000000000000000000000000000"
eip191_header = b"\x19\x01"
eip712_domain_separator_schema_hash = keccak(
b"EIP712Domain("
+ b"string name,"
+ b"string version,"
+ b"uint256 chainId,"
+ b"address verifyingContract"
+ b")"
)
eip712_domain_struct_header = (
eip712_domain_separator_schema_hash
+ keccak(b"0x Protocol")
+ keccak(b"3.0.0")
)
eip712_order_schema_hash = keccak(
b"Order("
+ b"address makerAddress,"
+ b"address takerAddress,"
+ b"address feeRecipientAddress,"
+ b"address senderAddress,"
+ b"uint256 makerAssetAmount,"
+ b"uint256 takerAssetAmount,"
+ b"uint256 makerFee,"
+ b"uint256 takerFee,"
+ b"uint256 expirationTimeSeconds,"
+ b"uint256 salt,"
+ b"bytes makerAssetData,"
+ b"bytes takerAssetData,"
+ b"bytes makerFeeAssetData,"
+ b"bytes takerFeeAssetData"
+ b")"
)
class SignatureType(Enum):
"""Enumeration of known signature types."""
ILLEGAL = 0
INVALID = auto()
EIP712 = auto()
ETH_SIGN = auto()
WALLET = auto()
VALIDATOR = auto()
PRE_SIGNED = auto()
N_SIGNATURE_TYPES = auto()
def generate_order_hash_hex(
order: Order, exchange_address: str, chain_id: int
) -> str:
"""Calculate the hash of the given order as a hexadecimal string.
:param order: The order to be hashed. Must conform to `the 0x order JSON schema <https://github.com/0xProject/0x-monorepo/blob/development/packages/json-schemas/schemas/order_schema.json>`_.
:param exchange_address: The address to which the 0x Exchange smart
contract has been deployed.
:returns: A string, of ASCII hex digits, representing the order hash.
Inputs and expected result below were copied from
@0x/order-utils/test/order_hash_test.ts
>>> generate_order_hash_hex(
... Order(
... makerAddress="0x0000000000000000000000000000000000000000",
... takerAddress="0x0000000000000000000000000000000000000000",
... feeRecipientAddress="0x0000000000000000000000000000000000000000",
... senderAddress="0x0000000000000000000000000000000000000000",
... makerAssetAmount="0",
... takerAssetAmount="0",
... makerFee="0",
... takerFee="0",
... expirationTimeSeconds="0",
... salt="0",
... makerAssetData=((0).to_bytes(1, byteorder='big') * 20),
... takerAssetData=((0).to_bytes(1, byteorder='big') * 20),
... makerFeeAssetData=((0).to_bytes(1, byteorder='big') * 20),
... takerFeeAssetData=((0).to_bytes(1, byteorder='big') * 20),
... ),
... exchange_address="0x1dc4c1cefef38a777b15aa20260a54e584b16c48",
... chain_id=1337
... )
'cb36e4fedb36508fb707e2c05e21bffc7a72766ccae93f8ff096693fff7f1714'
""" # noqa: E501 (line too long)
assert_is_address(exchange_address, "exchange_address")
assert_valid(
order_to_jsdict(order, chain_id, exchange_address), "/orderSchema"
)
def pad_20_bytes_to_32(twenty_bytes: bytes):
return bytes(12) + twenty_bytes
def int_to_32_big_endian_bytes(i: int):
return i.to_bytes(32, byteorder="big")
eip712_domain_struct_hash = keccak(
_Constants.eip712_domain_struct_header
+ int_to_32_big_endian_bytes(int(chain_id))
+ pad_20_bytes_to_32(to_bytes(hexstr=exchange_address))
)
def ensure_bytes(str_or_bytes: Union[str, bytes]) -> bytes:
return (
to_bytes(hexstr=cast(bytes, str_or_bytes))
if isinstance(str_or_bytes, str)
else str_or_bytes
)
eip712_order_struct_hash = keccak(
_Constants.eip712_order_schema_hash
+ pad_20_bytes_to_32(to_bytes(hexstr=order["makerAddress"]))
+ pad_20_bytes_to_32(to_bytes(hexstr=order["takerAddress"]))
+ pad_20_bytes_to_32(to_bytes(hexstr=order["feeRecipientAddress"]))
+ pad_20_bytes_to_32(to_bytes(hexstr=order["senderAddress"]))
+ int_to_32_big_endian_bytes(int(order["makerAssetAmount"]))
+ int_to_32_big_endian_bytes(int(order["takerAssetAmount"]))
+ int_to_32_big_endian_bytes(int(order["makerFee"]))
+ int_to_32_big_endian_bytes(int(order["takerFee"]))
+ int_to_32_big_endian_bytes(int(order["expirationTimeSeconds"]))
+ int_to_32_big_endian_bytes(int(order["salt"]))
+ keccak(ensure_bytes(order["makerAssetData"]))
+ keccak(ensure_bytes(order["takerAssetData"]))
+ keccak(ensure_bytes(order["makerFeeAssetData"]))
+ keccak(ensure_bytes(order["takerFeeAssetData"]))
)
return keccak(
_Constants.eip191_header
+ eip712_domain_struct_hash
+ eip712_order_struct_hash
).hex()
def is_valid_signature(
provider: BaseProvider, data: str, signature: str, signer_address: str
) -> bool:
"""Check the validity of the supplied signature.
Check if the supplied `signature`:code: corresponds to signing `data`:code:
with the private key corresponding to `signer_address`:code:.
:param provider: A Web3 provider able to access the 0x Exchange contract.
:param data: The hex encoded data signed by the supplied signature.
:param signature: The hex encoded signature.
:param signer_address: The hex encoded address that signed the data to
produce the supplied signature.
:returns: Tuple consisting of a boolean and a string. Boolean is true if
valid, false otherwise. If false, the string describes the reason.
>>> is_valid_signature(
... Web3.HTTPProvider("http://127.0.0.1:8545"),
... '0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b0',
... '0x1B61a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc3340349190569279751135161d22529dc25add4f6069af05be04cacbda2ace225403',
... '0x5409ed021d9299bf6814279a6a1411a7e866a631',
... )
True
""" # noqa: E501 (line too long)
assert_is_provider(provider, "provider")
assert_is_hex_string(data, "data")
assert_is_hex_string(signature, "signature")
assert_is_address(signer_address, "signer_address")
return Exchange(
provider,
chain_to_addresses(
ChainId(
int(Web3(provider).eth.chainId) # pylint: disable=no-member
)
).exchange,
).is_valid_hash_signature.call(
bytes.fromhex(remove_0x_prefix(HexStr(data))),
to_checksum_address(signer_address),
bytes.fromhex(remove_0x_prefix(HexStr(signature))),
)
class ECSignature(TypedDict):
"""Object representation of an elliptic curve signature's parameters."""
v: int
r: str
s: str
def _parse_signature_hex_as_vrs(signature_hex: str) -> ECSignature:
"""Parse signature hex as a concatentation of EC parameters ordered V, R, S.
>>> _parse_signature_hex_as_vrs('0x1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b03')
{'v': 27, 'r': '117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d87287113', 's': '7feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b'}
""" # noqa: E501 (line too long)
signature: ECSignature = {
"v": int(signature_hex[2:4], 16),
"r": signature_hex[4:68],
"s": signature_hex[68:132],
}
if signature["v"] == 0 or signature["v"] == 1:
signature["v"] = signature["v"] + 27
return signature
def _parse_signature_hex_as_rsv(signature_hex: str) -> ECSignature:
"""Parse signature hex as a concatentation of EC parameters ordered R, S, V.
>>> _parse_signature_hex_as_rsv('0x117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b00')
{'r': '117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d87287113', 's': '7feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b', 'v': 27}
""" # noqa: E501 (line too long)
signature: ECSignature = {
"r": signature_hex[2:66],
"s": signature_hex[66:130],
"v": int(signature_hex[130:132], 16),
}
if signature["v"] == 0 or signature["v"] == 1:
signature["v"] = signature["v"] + 27
return signature
def _convert_ec_signature_to_vrs_hex(signature: ECSignature) -> str:
"""Convert elliptic curve signature object to hex hash string.
>>> _convert_ec_signature_to_vrs_hex(
... {
... 'r': '117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d87287113',
... 's': '7feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b',
... 'v': 27
... }
... )
'0x1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b'
""" # noqa: E501 (line too long)
return (
"0x"
+ signature["v"].to_bytes(1, byteorder="big").hex()
+ signature["r"]
+ signature["s"]
)
def sign_hash(
web3_or_provider: Union[Web3, BaseProvider],
signer_address: str,
hash_hex: str,
) -> str:
"""Sign a message with the given hash, and return the signature.
:param web3_or_provider: Either an instance of `web3.Web3`:code: or
`web3.providers.base.BaseProvider`:code:
:param signer_address: The address of the signing account.
:param hash_hex: A hex string representing the hash, like that returned
from `generate_order_hash_hex()`:code:.
:returns: A string, of ASCII hex digits, representing the signature.
>>> provider = Web3.HTTPProvider("http://127.0.0.1:8545")
>>> sign_hash(
... provider,
... Web3(provider).geth.personal.listAccounts()[0],
... '0x34decbedc118904df65f379a175bb39ca18209d6ce41d5ed549d54e6e0a95004',
... )
'0x1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b03'
""" # noqa: E501 (line too long)
web3_instance = None
if isinstance(web3_or_provider, BaseProvider):
web3_instance = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3_instance = web3_or_provider
else:
raise TypeError(
"Expected parameter 'web3_or_provider' to be an instance of either"
+ " Web3 or BaseProvider"
)
assert_is_address(signer_address, "signer_address")
assert_is_hex_string(hash_hex, "hash_hex")
# false positive from pylint: disable=no-member
signature = web3_instance.eth.sign( # type: ignore
signer_address, hexstr=hash_hex.replace("0x", "")
).hex()
valid_v_param_values = [27, 28]
# HACK: There is no consensus on whether the signatureHex string should be
# formatted as v + r + s OR r + s + v, and different clients (even
# different versions of the same client) return the signature params in
# different orders. In order to support all client implementations, we
# parse the signature in both ways, and evaluate if either one is a valid
# signature. r + s + v is the most prevalent format from eth_sign, so we
# attempt this first.
ec_signature = _parse_signature_hex_as_rsv(signature)
if ec_signature["v"] in valid_v_param_values:
signature_as_vrst_hex = (
_convert_ec_signature_to_vrs_hex(ec_signature)
+ _Constants.SignatureType.ETH_SIGN.value.to_bytes(
1, byteorder="big"
).hex()
)
valid = is_valid_signature(
web3_instance.provider,
hash_hex,
signature_as_vrst_hex,
signer_address,
)
if valid is True:
return signature_as_vrst_hex
ec_signature = _parse_signature_hex_as_vrs(signature)
if ec_signature["v"] in valid_v_param_values:
signature_as_vrst_hex = (
_convert_ec_signature_to_vrs_hex(ec_signature)
+ _Constants.SignatureType.ETH_SIGN.value.to_bytes(
1, byteorder="big"
).hex()
)
valid = is_valid_signature(
web3_instance.provider,
hash_hex,
signature_as_vrst_hex,
signer_address,
)
if valid is True:
return signature_as_vrst_hex
raise RuntimeError(
"Signature returned from web3 provider is in an unknown format. "
+ "Signature was: {signature}"
)
def sign_hash_to_bytes(
web3_or_provider: Union[Web3, BaseProvider],
signer_address: str,
hash_hex: str,
) -> bytes:
"""Sign a message with the given hash, and return the signature.
>>> provider = Web3.HTTPProvider("http://127.0.0.1:8545")
>>> sign_hash_to_bytes(
... provider,
... Web3(provider).geth.personal.listAccounts()[0],
... '0x34decbedc118904df65f379a175bb39ca18209d6ce41d5ed549d54e6e0a95004',
... ).decode(encoding='utf_8')
'1b117902c86dfb95fe0d1badd983ee166ad259b27acb220174cbb4460d872871137feabdfe76e05924b484789f79af4ee7fa29ec006cedce1bbf369320d034e10b03'
""" # noqa: E501 (line too long)
return remove_0x_prefix(
HexStr(sign_hash(web3_or_provider, signer_address, hash_hex))
).encode(encoding="utf_8")
| 0x-order-utils | /0x_order_utils-4.0.1-py3-none-any.whl/zero_ex/order_utils/__init__.py | __init__.py |
from ZeroEx import ZeroEx
client = ZeroEx()
# /swap/v1/tokens
tokens = client.get_tokens()
print(tokens)
# /swap/v1/price
price = client.get_price(1, "BTC", "ETH")
print(price)
# /swap/v1/prices
prices = client.get_prices()
print(prices) | 0x-python | /0x_python-1.0.16-py3-none-any.whl/ZeroEx/test_0x.py | test_0x.py |
from .ZeroEx import ZeroEx | 0x-python | /0x_python-1.0.16-py3-none-any.whl/ZeroEx/__init__.py | __init__.py |
import requests
import optparse
import urllib
HOST = "https://api.0x.org"
class ZeroEx:
"""
0x API
...
Attributes
----------
Methods
-------
"""
def __init__(self, host="https://api.0x.org", verbose=False):
self.host = host
self.verbose = verbose
self.session = requests.Session()
def close(self):
self.session.close()
def request(self, method, path, query):
# cut any accidental / from in front of path
if str(path)[:1] == "//": path = path[1:]
url = self.host + path
if query:
url += '?' + urllib.parse.urlencode(query)
if self.verbose:
print()
print(method, url)
if query != "":
print('query: '+str(query))
headers = {
'Content-Type': 'application/json'
}
self.session.headers = headers
response = self.session.request(method, url)
if response.status_code == 200:
return response.json()
elif response.content:
raise Exception(str(response.status_code) + ": " + response.reason + " " + str(response.content))
else:
raise Exception(str(response.status_code) + ": " + response.reason)
#############################################################################################
# /swap/v1/price
def get_price(self, sellAmountInWei, sellToken, buyToken, takerAddress=None, affiliateAddress=None, asJSON=False):
qs = {
'sellToken': sellToken,
'buyToken': buyToken,
'sellAmount': sellAmountInWei
}
if takerAddress:
qs['takerAddress'] = takerAddress
if affiliateAddress:
qs['affiliateAddress'] = affiliateAddress
# 'skipValidation': True, # enabled by default
return self.request('GET', '/swap/v1/price', qs)
# sellToken (Optional, defaults to "WETH") The ERC20 token address or symbol of the token
# you want to get the price of tokens in. "ETH" can be provided as a valid sellToken.
# /swap/v1/prices
def get_prices(self, sellToken="WETH"):
qs = {
'sellToken': sellToken
}
return list(self.request('GET', '/swap/v1/prices', qs)['records'])
# /swap/v1/tokens
def get_tokens(self):
return list(self.request('GET', '/swap/v1/tokens', None)['records'])
# /swap/v1/quote
def get_quote(self, amountInWei, sellToken, buyToken):
qs = {
'sellToken': sellToken,
'buyToken': buyToken,
'sellAmount': amountInWei,
}
return self.request('GET', '/swap/v1/quote', qs)
#############################################################################################
# def fill_quote(self, quote, contract, _from):
# # Fill the quote through 0x provided contract method
# receipt = contract.methods.fillQuote(
# quote.sellTokenAddress,
# quote.buyTokenAddress,
# quote.allowanceTarget,
# quote.to,
# quote.data
# ).send({
# 'from': _from,
# 'value': quote.value,
# 'gasPrice': quote.gasPrice,
# })
# print("response: {}".format(receipt))
# return receipt
#############################################################################################
def main():
parser = optparse.OptionParser()
parser.add_option('-h', '--host', dest="host", help="Host for request", default=HOST)
parser.add_option('-m', '--method', dest="method", help="Method for request", default="GET")
parser.add_option('-p', '--path', dest="path", help="Path for request", default="/")
parser.add_option('-q', '--params', dest="params", help="Parameters for request")
parser.add_option('-d', '--body', dest="body", help="Body for request")
options, args = parser.parse_args()
ZeroEx = ZeroEx()
query = ''
if options.params is not None:
query = options.params
try:
response = ZeroEx.request(options.method, options.path, query, options.body)
except Exception as ex:
print("Unexpected error:", ex)
exit(1)
print(response)
exit(0)
if __name__ == "__main__":
main()
| 0x-python | /0x_python-1.0.16-py3-none-any.whl/ZeroEx/ZeroEx.py | ZeroEx.py |
# 0x-sra-client
A Python client for interacting with servers conforming to [the Standard Relayer API specification](https://github.com/0xProject/0x-monorepo/tree/development/packages/sra-spec).
Read the [documentation](http://0x-sra-client-py.s3-website-us-east-1.amazonaws.com/)
# Schemas
The [JSON schemas](http://json-schema.org/) for the API payloads and responses can be found in [@0xproject/json-schemas](https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas). Examples of each payload and response can be found in the 0x.js library's [test suite](https://github.com/0xProject/0x-monorepo/blob/development/packages/json-schemas/test/schema_test.ts#L1).
```bash
pip install 0x-json-schemas
```
You can easily validate your API's payloads and responses using the [0x-json-schemas](https://github.com/0xProject/0x.js/tree/development/python-packages/json_schemas) package:
```python
from zero_ex.json_schemas import assert_valid
from zero_ex.order_utils import Order
order: Order = {
'makerAddress': "0x0000000000000000000000000000000000000000",
'takerAddress': "0x0000000000000000000000000000000000000000",
'feeRecipientAddress': "0x0000000000000000000000000000000000000000",
'senderAddress': "0x0000000000000000000000000000000000000000",
'makerAssetAmount': "1000000000000000000",
'takerAssetAmount': "1000000000000000000",
'makerFee': "0",
'takerFee': "0",
'expirationTimeSeconds': "12345",
'salt': "12345",
'makerAssetData': "0x0000000000000000000000000000000000000000",
'takerAssetData': "0x0000000000000000000000000000000000000000",
'exchangeAddress': "0x0000000000000000000000000000000000000000",
}
assert_valid(order, "/orderSchema")
```
# Pagination
Requests that return potentially large collections should respond to the **?page** and **?perPage** parameters. For example:
```bash
$ curl https://api.example-relayer.com/v2/asset_pairs?page=3&perPage=20
```
Page numbering should be 1-indexed, not 0-indexed. If a query provides an unreasonable (ie. too high) `perPage` value, the response can return a validation error as specified in the [errors section](#section/Errors). If the query specifies a `page` that does not exist (ie. there are not enough `records`), the response should just return an empty `records` array.
All endpoints that are paginated should return a `total`, `page`, `perPage` and a `records` value in the top level of the collection. The value of `total` should be the total number of records for a given query, whereas `records` should be an array representing the response to the query for that page. `page` and `perPage`, are the same values that were specified in the request. See the note in [miscellaneous](#section/Misc.) about formatting `snake_case` vs. `lowerCamelCase`.
These requests include the [`/v2/asset_pairs`](#operation/getAssetPairs), [`/v2/orders`](#operation/getOrders), [`/v2/fee_recipients`](#operation/getFeeRecipients) and [`/v2/orderbook`](#operation/getOrderbook) endpoints.
# Network Id
All requests should be able to specify a **?networkId** query param for all supported networks. For example:
```bash
$ curl https://api.example-relayer.com/v2/asset_pairs?networkId=1
```
If the query param is not provided, it should default to **1** (mainnet).
Networks and their Ids:
| Network Id | Network Name |
| ---------- | ------------ |
| 1 | Mainnet |
| 42 | Kovan |
| 3 | Ropsten |
| 4 | Rinkeby |
If a certain network is not supported, the response should **400** as specified in the [error response](#section/Errors) section. For example:
```json
{
\"code\": 100,
\"reason\": \"Validation failed\",
\"validationErrors\": [
{
\"field\": \"networkId\",
\"code\": 1006,
\"reason\": \"Network id 42 is not supported\"
}
]
}
```
# Link Header
A [Link Header](https://tools.ietf.org/html/rfc5988) can be included in a response to provide clients with more context about paging
For example:
```bash
Link: <https://api.example-relayer.com/v2/asset_pairs?page=3&perPage=20>; rel=\"next\",
<https://api.github.com/user/repos?page=10&perPage=20>; rel=\"last\"
```
This `Link` response header contains one or more Hypermedia link relations.
The possible `rel` values are:
| Name | Description |
| ----- | ------------------------------------------------------------- |
| next | The link relation for the immediate next page of results. |
| last | The link relation for the last page of results. |
| first | The link relation for the first page of results. |
| prev | The link relation for the immediate previous page of results. |
# Rate Limits
Rate limit guidance for clients can be optionally returned in the response headers:
| Header Name | Description |
| --------------------- | ---------------------------------------------------------------------------- |
| X-RateLimit-Limit | The maximum number of requests you're permitted to make per hour. |
| X-RateLimit-Remaining | The number of requests remaining in the current rate limit window. |
| X-RateLimit-Reset | The time at which the current rate limit window resets in UTC epoch seconds. |
For example:
```bash
$ curl -i https://api.example-relayer.com/v2/asset_pairs
HTTP/1.1 200 OK
Date: Mon, 20 Oct 2017 12:30:06 GMT
Status: 200 OK
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 56
X-RateLimit-Reset: 1372700873
```
When a rate limit is exceeded, a status of **429 Too Many Requests** should be returned.
# Errors
Unless the spec defines otherwise, errors to bad requests should respond with HTTP 4xx or status codes.
## Common error codes
| Code | Reason |
| ---- | --------------------------------------- |
| 400 | Bad Request – Invalid request format |
| 404 | Not found |
| 429 | Too many requests - Rate limit exceeded |
| 500 | Internal Server Error |
| 501 | Not Implemented |
## Error reporting format
For all **400** responses, see the [error response schema](https://github.com/0xProject/0x-monorepo/blob/development/packages/json-schemas/schemas/relayer_api_error_response_schema.ts#L1).
```json
{
\"code\": 101,
\"reason\": \"Validation failed\",
\"validationErrors\": [
{
\"field\": \"maker\",
\"code\": 1002,
\"reason\": \"Invalid address\"
}
]
}
```
General error codes:
```bash
100 - Validation Failed
101 - Malformed JSON
102 - Order submission disabled
103 - Throttled
```
Validation error codes:
```bash
1000 - Required field
1001 - Incorrect format
1002 - Invalid address
1003 - Address not supported
1004 - Value out of range
1005 - Invalid signature or hash
1006 - Unsupported option
```
# Asset Data Encoding
As we now support multiple [token transfer proxies](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#assetproxy), the identifier of which proxy to use for the token transfer must be encoded, along with the token information. Each proxy in 0x v2 has a unique identifier. If you're using 0x.js there will be helper methods for this [encoding](https://0x.org/docs/tools/0x.js#zeroEx-encodeERC20AssetData) and [decoding](https://0x.org/docs/tools/0x.js#zeroEx-decodeAssetProxyId).
The identifier for the Proxy uses a similar scheme to [ABI function selectors](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector).
```js
// ERC20 Proxy ID 0xf47261b0
bytes4(keccak256('ERC20Token(address)'));
// ERC721 Proxy ID 0x02571792
bytes4(keccak256('ERC721Token(address,uint256)'));
```
Asset data is encoded using [ABI encoding](https://solidity.readthedocs.io/en/develop/abi-spec.html).
For example, encoding the ERC20 token contract (address: 0x1dc4c1cefef38a777b15aa20260a54e584b16c48) using the ERC20 Transfer Proxy (id: 0xf47261b0) would be:
```bash
0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48
```
Encoding the ERC721 token contract (address: `0x371b13d97f4bf77d724e78c16b7dc74099f40e84`), token id (id: `99`, which hex encoded is `0x63`) and the ERC721 Transfer Proxy (id: 0x02571792) would be:
```bash
0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063
```
For more information see [the Asset Proxy](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#erc20proxy) section of the v2 spec and the [Ethereum ABI Spec](https://solidity.readthedocs.io/en/develop/abi-spec.html).
# Meta Data in Order Responses
In v2 of the standard relayer API we added the `metaData` field. It is meant to provide a standard place for relayers to put optional, custom or non-standard fields that may of interest to the consumer of the API.
A good example of such a field is `remainingTakerAssetAmount`, which is a convenience field that communicates how much of a 0x order is potentially left to be filled. Unlike the other fields in a 0x order, it is not guaranteed to be correct as it is derived from whatever mechanism the implementer (ie. the relayer) is using. While convenient for prototyping and low stakes situations, we recommend validating the value of the field by checking the state of the blockchain yourself.
# Misc.
- All requests and responses should be of **application/json** content type
- All token amounts are sent in amounts of the smallest level of precision (base units). (e.g if a token has 18 decimal places, selling 1 token would show up as selling `'1000000000000000000'` units by this API).
- All addresses are sent as lower-case (non-checksummed) Ethereum addresses with the `0x` prefix.
- All parameters are to be written in `lowerCamelCase`.
This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: 2.0.0
- Package version: 1.0.0
- Build package: org.openapitools.codegen.languages.PythonClientCodegen
## Requirements.
Python 2.7 and 3.4+
## Installation & Usage
### pip install
If the python package is hosted on Github, you can install directly from Github
```sh
pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git
```
(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`)
Then import the package:
```python
import sra_client
```
### Setuptools
Install via [Setuptools](http://pypi.python.org/pypi/setuptools).
```sh
python setup.py install --user
```
(or `sudo python setup.py install` to install the package for all users)
Then import the package:
```python
import sra_client
```
## Getting Started
Please follow the [installation procedure](#installation--usage) and then run the following:
```python
from __future__ import print_function
import time
import sra_client
from sra_client.rest import ApiException
from pprint import pprint
# create an instance of the API class
api_instance = sra_client.DefaultApi(sra_client.ApiClient(configuration))
asset_data_a = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | The assetData value for the first asset in the pair. (optional)
asset_data_b = 0x0257179264389b814a946f3e92105513705ca6b990 # str | The assetData value for the second asset in the pair. (optional)
network_id = 42 # float | The id of the Ethereum network (optional) (default to 1)
page = 3 # float | The number of the page to request in the collection. (optional) (default to 1)
per_page = 10 # float | The number of records to return per page. (optional) (default to 100)
try:
api_response = api_instance.get_asset_pairs(asset_data_a=asset_data_a, asset_data_b=asset_data_b, network_id=network_id, page=page, per_page=per_page)
pprint(api_response)
except ApiException as e:
print("Exception when calling DefaultApi->get_asset_pairs: %s\n" % e)
```
## Contributing
We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository.
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
### Install Code and Dependencies
Ensure that you have installed Python >=3.6, Docker, and docker-compose. Then:
```bash
pip install -e .[dev]
```
### Test
Tests depend on a running instance of 0x-launch-kit-backend, backed by a Ganache node with the 0x contracts deployed in it. For convenience, a docker-compose file is provided that creates this environment. And a shortcut is provided to interface with that file: `./setup.py start_test_relayer` will start those services. With them running, the tests can be run with `./setup.py test`. When you're done with testing, you can `./setup.py stop_test_relayer`.
### Clean
`./setup.py clean --all`
### Lint
`./setup.py lint`
### Build Documentation
`./setup.py build_sphinx`
### More
See `./setup.py --help-commands` for more info.
## Documentation for API Endpoints
All URIs are relative to _http://localhost_
| Class | Method | HTTP request | Description |
| ------------ | --------------------------------------------------------------- | ----------------------------- | ----------- |
| _DefaultApi_ | [**get_asset_pairs**](docs/DefaultApi.md#get_asset_pairs) | **GET** /v2/asset_pairs |
| _DefaultApi_ | [**get_fee_recipients**](docs/DefaultApi.md#get_fee_recipients) | **GET** /v2/fee_recipients |
| _DefaultApi_ | [**get_order**](docs/DefaultApi.md#get_order) | **GET** /v2/order/{orderHash} |
| _DefaultApi_ | [**get_order_config**](docs/DefaultApi.md#get_order_config) | **POST** /v2/order_config |
| _DefaultApi_ | [**get_orderbook**](docs/DefaultApi.md#get_orderbook) | **GET** /v2/orderbook |
| _DefaultApi_ | [**get_orders**](docs/DefaultApi.md#get_orders) | **GET** /v2/orders |
| _DefaultApi_ | [**post_order**](docs/DefaultApi.md#post_order) | **POST** /v2/order |
## Documentation For Models
- [OrderSchema](docs/OrderSchema.md)
- [PaginatedCollectionSchema](docs/PaginatedCollectionSchema.md)
- [RelayerApiAssetDataPairsResponseSchema](docs/RelayerApiAssetDataPairsResponseSchema.md)
- [RelayerApiAssetDataTradeInfoSchema](docs/RelayerApiAssetDataTradeInfoSchema.md)
- [RelayerApiErrorResponseSchema](docs/RelayerApiErrorResponseSchema.md)
- [RelayerApiErrorResponseSchemaValidationErrors](docs/RelayerApiErrorResponseSchemaValidationErrors.md)
- [RelayerApiFeeRecipientsResponseSchema](docs/RelayerApiFeeRecipientsResponseSchema.md)
- [RelayerApiOrderConfigPayloadSchema](docs/RelayerApiOrderConfigPayloadSchema.md)
- [RelayerApiOrderConfigResponseSchema](docs/RelayerApiOrderConfigResponseSchema.md)
- [RelayerApiOrderSchema](docs/RelayerApiOrderSchema.md)
- [RelayerApiOrderbookResponseSchema](docs/RelayerApiOrderbookResponseSchema.md)
- [RelayerApiOrdersChannelSubscribePayloadSchema](docs/RelayerApiOrdersChannelSubscribePayloadSchema.md)
- [RelayerApiOrdersChannelSubscribeSchema](docs/RelayerApiOrdersChannelSubscribeSchema.md)
- [RelayerApiOrdersChannelUpdateSchema](docs/RelayerApiOrdersChannelUpdateSchema.md)
- [RelayerApiOrdersResponseSchema](docs/RelayerApiOrdersResponseSchema.md)
- [SignedOrderSchema](docs/SignedOrderSchema.md)
## Documentation For Authorization
All endpoints do not require authorization.
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/README.md | README.md |
#!/usr/bin/env python
# coding: utf-8
"""setuptools module for sra_client package."""
# pylint: disable=import-outside-toplevel
# we import things outside of top-level because 3rd party libs may not yet be
# installed when you invoke this script
import subprocess # nosec
import distutils.command.build_py
from distutils.command.clean import clean
from shutil import rmtree
from sys import exit # pylint: disable=redefined-builtin
from urllib.request import urlopen
from urllib.error import URLError
from setuptools import setup, find_packages # noqa: H301
from setuptools.command.test import test as TestCommand
NAME = "0x-sra-client"
VERSION = "4.0.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
with open("README.md", "r") as file_handle:
README_MD = file_handle.read()
REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"]
class CleanCommandExtension(clean):
"""Custom command to do custom cleanup."""
def run(self):
"""Run the regular clean, followed by our custom commands."""
super().run()
rmtree("__pycache__", ignore_errors=True)
rmtree(".mypy_cache", ignore_errors=True)
rmtree(".tox", ignore_errors=True)
rmtree(".pytest_cache", ignore_errors=True)
rmtree("src/0x_sra_client.egg-info", ignore_errors=True)
rmtree("build", ignore_errors=True)
rmtree("dist", ignore_errors=True)
subprocess.check_call( # nosec
("docker-compose -f test/relayer/docker-compose.yml down").split()
)
subprocess.check_call( # nosec
("docker-compose -f test/relayer/docker-compose.yml rm").split()
)
class TestCommandExtension(TestCommand):
"""Run pytest tests."""
def run_tests(self):
"""Invoke pytest."""
import pytest
exit(pytest.main(["--doctest-modules", "-rapP"]))
# show short test summary at end ^
# above call commented out due to a problem with launch kit,
# documented at
# https://github.com/0xProject/0x-launch-kit-backend/issues/73
class TestPublishCommand(distutils.command.build_py.build_py):
"""Custom command to publish to test.pypi.org."""
description = (
"Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first."
)
def run(self):
"""Run twine to upload to test.pypi.org."""
subprocess.check_call( # nosec
(
"twine upload --repository-url https://test.pypi.org/legacy/"
+ " --verbose dist/*"
).split()
)
class StartTestRelayerCommand(distutils.command.build_py.build_py):
"""Custom command to boot up a local 0x-launch-kit-backend in docker."""
description = "Run launch-kit daemon to support tests."
def run(self):
"""Run `docker-compose up`."""
subprocess.call( # nosec
("docker-compose -f test/relayer/docker-compose.yml pull").split()
)
subprocess.call( # nosec
("docker-compose -f test/relayer/docker-compose.yml up -d").split()
)
launch_kit_ready = False
print(
"Waiting for Launch Kit Backend to start accepting connections...",
flush=True,
)
while not launch_kit_ready:
try:
launch_kit_ready = (
urlopen( # nosec
"http://localhost:3000/v3/asset_pairs"
).getcode()
== 200
)
except URLError:
continue
print("done")
class StopTestRelayerCommand(distutils.command.build_py.build_py):
"""Custom command to tear down the 0x-launch-kit-backend test relayer."""
description = "Tear down launch-kit daemon."
def run(self):
"""Run `docker-compose down`."""
subprocess.call( # nosec
("docker-compose -f test/relayer/docker-compose.yml down").split()
)
class LintCommand(distutils.command.build_py.build_py):
"""Custom setuptools command class for running linters."""
description = "Run linters"
def run(self):
"""Run linter shell commands."""
lint_targets = "test src/zero_ex/sra_client/__init__.py setup.py"
lint_commands = [
# formatter:
(
f"black --line-length 79 --check --diff test {lint_targets}"
).split(),
# style guide checker (formerly pep8):
f"pycodestyle {lint_targets}".split(),
# docstring style checker:
f"pydocstyle {lint_targets}".split(),
# static type checker:
f"bandit -r {lint_targets}".split(),
# general linter:
f"pylint {lint_targets}".split(),
# pylint takes relatively long to run, so it runs last, to enable
# fast failures.
]
for lint_command in lint_commands:
print(
"Running lint command `", " ".join(lint_command).strip(), "`"
)
subprocess.check_call(lint_command) # nosec
class PublishCommand(distutils.command.build_py.build_py):
"""Custom command to publish to pypi.org."""
description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first."
def run(self):
"""Run twine to upload to pypi.org."""
subprocess.check_call("twine upload dist/*".split()) # nosec
class PublishDocsCommand(distutils.command.build_py.build_py):
"""Custom command to publish docs to S3."""
description = (
"Publish docs to "
+ "http://0x-sra-client-py.s3-website-us-east-1.amazonaws.com/"
)
def run(self):
"""Run npm package `discharge` to build & upload docs."""
subprocess.check_call("discharge deploy".split()) # nosec
setup(
name=NAME,
version=VERSION,
description="Standard Relayer REST API Client",
author="F. Eugene Aumson",
author_email="feuGeneA@users.noreply.github.com",
url=(
"https://github.com/0xproject/0x-monorepo/tree/development"
"/python-packages/sra_client"
),
keywords=["OpenAPI", "OpenAPI-Generator", "Standard Relayer REST API"],
install_requires=REQUIRES,
namespace_packages=["zero_ex"],
packages=find_packages("src"),
package_dir={"": "src"},
include_package_data=True,
long_description=README_MD,
long_description_content_type="text/markdown",
cmdclass={
"clean": CleanCommandExtension,
"test_publish": TestPublishCommand,
"publish": PublishCommand,
"start_test_relayer": StartTestRelayerCommand,
"stop_test_relayer": StopTestRelayerCommand,
"lint": LintCommand,
"publish_docs": PublishDocsCommand,
"test": TestCommandExtension,
},
extras_require={
"dev": [
"0x-contract-artifacts",
"0x-contract-addresses",
"0x-contract-wrappers",
"0x-order-utils",
"web3",
"bandit",
"black",
"coverage",
"coveralls",
"pycodestyle",
"pydocstyle",
"pylint",
"pytest",
"sphinx",
"sphinx-autodoc-typehints",
]
},
command_options={
"build_sphinx": {
"source_dir": ("setup.py", "src"),
"build_dir": ("setup.py", "build/docs"),
"warning_is_error": ("setup.py", "true"),
}
},
)
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/setup.py | setup.py |
"""0x Python API."""
__import__("pkg_resources").declare_namespace(__name__) # type: ignore
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/__init__.py | __init__.py |
# coding: utf-8
from __future__ import absolute_import
import datetime
import json
import mimetypes
from multiprocessing.pool import ThreadPool
import os
import re
import tempfile
# python 2 and python 3 compatibility library
import six
from six.moves.urllib.parse import quote
from zero_ex.sra_client.configuration import Configuration
import zero_ex.sra_client.models
from zero_ex.sra_client import rest
class ApiClient(object):
"""Generic API client for OpenAPI client library builds.
OpenAPI generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the methods and models for each application are generated from the OpenAPI
templates.
NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
:param configuration: .Configuration object for this client
:param header_name: a header to pass when making calls to the API.
:param header_value: a header value to pass when making calls to
the API.
:param cookie: a cookie to include in the header when making calls
to the API
:param pool_threads: The number of threads to use for async requests
to the API. More threads means more concurrent API requests.
"""
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
NATIVE_TYPES_MAPPING = {
"int": int,
"long": int if six.PY3 else long, # noqa: F821
"float": float,
"str": str,
"bool": bool,
"date": datetime.date,
"datetime": datetime.datetime,
"object": object,
}
_pool = None
def __init__(
self,
configuration=None,
header_name=None,
header_value=None,
cookie=None,
pool_threads=None,
):
if configuration is None:
configuration = Configuration()
self.configuration = configuration
self.pool_threads = pool_threads
self.rest_client = rest.RESTClientObject(configuration)
self.default_headers = {}
if header_name is not None:
self.default_headers[header_name] = header_value
self.cookie = cookie
# Set default User-Agent.
self.user_agent = "OpenAPI-Generator/1.0.0/python"
def __del__(self):
if self._pool:
self._pool.close()
self._pool.join()
self._pool = None
@property
def pool(self):
"""Create thread pool on first request
avoids instantiating unused threadpool for blocking clients.
"""
if self._pool is None:
self._pool = ThreadPool(self.pool_threads)
return self._pool
@property
def user_agent(self):
"""User agent for this API client"""
return self.default_headers["User-Agent"]
@user_agent.setter
def user_agent(self, value):
self.default_headers["User-Agent"] = value
def set_default_header(self, header_name, header_value):
self.default_headers[header_name] = header_value
def __call_api(
self,
resource_path,
method,
path_params=None,
query_params=None,
header_params=None,
body=None,
post_params=None,
files=None,
response_type=None,
auth_settings=None,
_return_http_data_only=None,
collection_formats=None,
_preload_content=True,
_request_timeout=None,
):
config = self.configuration
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
header_params["Cookie"] = self.cookie
if header_params:
header_params = self.sanitize_for_serialization(header_params)
header_params = dict(
self.parameters_to_tuples(header_params, collection_formats)
)
# path parameters
if path_params:
path_params = self.sanitize_for_serialization(path_params)
path_params = self.parameters_to_tuples(
path_params, collection_formats
)
for k, v in path_params:
# specified safe chars, encode everything
resource_path = resource_path.replace(
"{%s}" % k,
quote(str(v), safe=config.safe_chars_for_path_param),
)
# query parameters
if query_params:
query_params = self.sanitize_for_serialization(query_params)
query_params = self.parameters_to_tuples(
query_params, collection_formats
)
# post parameters
if post_params or files:
post_params = self.prepare_post_parameters(post_params, files)
post_params = self.sanitize_for_serialization(post_params)
post_params = self.parameters_to_tuples(
post_params, collection_formats
)
# auth setting
self.update_params_for_auth(header_params, query_params, auth_settings)
# body
if body:
body = self.sanitize_for_serialization(body)
# request url
url = self.configuration.host + resource_path
# perform request and return response
response_data = self.request(
method,
url,
query_params=query_params,
headers=header_params,
post_params=post_params,
body=body,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
)
self.last_response = response_data
return_data = response_data
if _preload_content:
# deserialize response data
if response_type:
return_data = self.deserialize(response_data, response_type)
else:
return_data = None
if _return_http_data_only:
return return_data
else:
return (
return_data,
response_data.status,
response_data.getheaders(),
)
def sanitize_for_serialization(self, obj):
"""Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date convert to string in iso8601 format.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is OpenAPI model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data.
"""
if obj is None:
return None
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, list):
return [
self.sanitize_for_serialization(sub_obj) for sub_obj in obj
]
elif isinstance(obj, tuple):
return tuple(
self.sanitize_for_serialization(sub_obj) for sub_obj in obj
)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
if isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `openapi_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
obj_dict = {
obj.attribute_map[attr]: getattr(obj, attr)
for attr, _ in six.iteritems(obj.openapi_types)
if getattr(obj, attr) is not None
}
return {
key: self.sanitize_for_serialization(val)
for key, val in six.iteritems(obj_dict)
}
def deserialize(self, response, response_type):
"""Deserializes response into an object.
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialized object, or string of class name.
:return: deserialized object.
"""
# handle file downloading
# save response body into a tmp file and return the instance
if response_type == "file":
return self.__deserialize_file(response)
# fetch data from response object
try:
data = json.loads(response.data)
except ValueError:
data = response.data
return self.__deserialize(data, response_type)
def __deserialize(self, data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if type(klass) == str:
if klass.startswith("list["):
sub_kls = re.match(r"list\[(.*)\]", klass).group(1)
return [
self.__deserialize(sub_data, sub_kls) for sub_data in data
]
if klass.startswith("dict("):
sub_kls = re.match(r"dict\(([^,]*), (.*)\)", klass).group(2)
return {
k: self.__deserialize(v, sub_kls)
for k, v in six.iteritems(data)
}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr(zero_ex.sra_client.models, klass)
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
elif klass == datetime.date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
return self.__deserialize_datatime(data)
else:
return self.__deserialize_model(data, klass)
def call_api(
self,
resource_path,
method,
path_params=None,
query_params=None,
header_params=None,
body=None,
post_params=None,
files=None,
response_type=None,
auth_settings=None,
async_req=None,
_return_http_data_only=None,
collection_formats=None,
_preload_content=True,
_request_timeout=None,
):
"""Makes the HTTP request (synchronous) and returns deserialized data.
To make an async_req request, set the async_req parameter.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param response: Response data type.
:param files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return:
If async_req parameter is True,
the request will be called asynchronously.
The method will return the request thread.
If parameter async_req is False or missing,
then the method will return the response directly.
"""
if not async_req:
return self.__call_api(
resource_path,
method,
path_params,
query_params,
header_params,
body,
post_params,
files,
response_type,
auth_settings,
_return_http_data_only,
collection_formats,
_preload_content,
_request_timeout,
)
else:
thread = self.pool.apply_async(
self.__call_api,
(
resource_path,
method,
path_params,
query_params,
header_params,
body,
post_params,
files,
response_type,
auth_settings,
_return_http_data_only,
collection_formats,
_preload_content,
_request_timeout,
),
)
return thread
def request(
self,
method,
url,
query_params=None,
headers=None,
post_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
):
"""Makes the HTTP request using RESTClient."""
if method == "GET":
return self.rest_client.GET(
url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers,
)
elif method == "HEAD":
return self.rest_client.HEAD(
url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers,
)
elif method == "OPTIONS":
return self.rest_client.OPTIONS(
url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
elif method == "POST":
return self.rest_client.POST(
url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
elif method == "PUT":
return self.rest_client.PUT(
url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
elif method == "PATCH":
return self.rest_client.PATCH(
url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
elif method == "DELETE":
return self.rest_client.DELETE(
url,
query_params=query_params,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
else:
raise ValueError(
"http method must be `GET`, `HEAD`, `OPTIONS`,"
" `POST`, `PATCH`, `PUT` or `DELETE`."
)
def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collections formatted
"""
new_params = []
if collection_formats is None:
collection_formats = {}
for k, v in (
six.iteritems(params) if isinstance(params, dict) else params
): # noqa: E501
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == "multi":
new_params.extend((k, value) for value in v)
else:
if collection_format == "ssv":
delimiter = " "
elif collection_format == "tsv":
delimiter = "\t"
elif collection_format == "pipes":
delimiter = "|"
else: # csv is the default
delimiter = ","
new_params.append(
(k, delimiter.join(str(value) for value in v))
)
else:
new_params.append((k, v))
return new_params
def prepare_post_parameters(self, post_params=None, files=None):
"""Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
if post_params:
params = post_params
if files:
for k, v in six.iteritems(files):
if not v:
continue
file_names = v if type(v) is list else [v]
for n in file_names:
with open(n, "rb") as f:
filename = os.path.basename(f.name)
filedata = f.read()
mimetype = (
mimetypes.guess_type(filename)[0]
or "application/octet-stream"
)
params.append(
tuple([k, tuple([filename, filedata, mimetype])])
)
return params
def select_header_accept(self, accepts):
"""Returns `Accept` based on an array of accepts provided.
:param accepts: List of headers.
:return: Accept (e.g. application/json).
"""
if not accepts:
return
accepts = [x.lower() for x in accepts]
if "application/json" in accepts:
return "application/json"
else:
return ", ".join(accepts)
def select_header_content_type(self, content_types):
"""Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return "application/json"
content_types = [x.lower() for x in content_types]
if "application/json" in content_types or "*/*" in content_types:
return "application/json"
else:
return content_types[0]
def update_params_for_auth(self, headers, querys, auth_settings):
"""Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param querys: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
"""
if not auth_settings:
return
for auth in auth_settings:
auth_setting = self.configuration.auth_settings().get(auth)
if auth_setting:
if not auth_setting["value"]:
continue
elif auth_setting["in"] == "header":
headers[auth_setting["key"]] = auth_setting["value"]
elif auth_setting["in"] == "query":
querys.append((auth_setting["key"], auth_setting["value"]))
else:
raise ValueError(
"Authentication token must be in `query` or `header`"
)
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
filename = re.search(
r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition
).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return six.text_type(data)
except TypeError:
return data
def __deserialize_object(self, value):
"""Return an original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string),
)
def __deserialize_datatime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object".format(string)
),
)
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
if not klass.openapi_types and not hasattr(
klass, "get_real_child_model"
):
return data
kwargs = {}
if klass.openapi_types is not None:
for attr, attr_type in six.iteritems(klass.openapi_types):
if (
data is not None
and klass.attribute_map[attr] in data
and isinstance(data, (list, dict))
):
value = data[klass.attribute_map[attr]]
kwargs[attr] = self.__deserialize(value, attr_type)
instance = klass(**kwargs)
if hasattr(instance, "get_real_child_model"):
klass_name = instance.get_real_child_model(data)
if klass_name:
instance = self.__deserialize(data, klass_name)
return instance
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/api_client.py | api_client.py |
# coding: utf-8
from __future__ import absolute_import
import io
import json
import logging
import re
import ssl
import certifi
# python 2 and python 3 compatibility library
import six
from six.moves.urllib.parse import urlencode
try:
import urllib3
except ImportError:
raise ImportError("OpenAPI Python client requires urllib3.")
logger = logging.getLogger(__name__)
class RESTResponse(io.IOBase):
def __init__(self, resp):
self.urllib3_response = resp
self.status = resp.status
self.reason = resp.reason
self.data = resp.data
def getheaders(self):
"""Returns a dictionary of the response headers."""
return self.urllib3_response.getheaders()
def getheader(self, name, default=None):
"""Returns a given response header."""
return self.urllib3_response.getheader(name, default)
class RESTClientObject(object):
def __init__(self, configuration, pools_size=4, maxsize=None):
# urllib3.PoolManager will pass all kw parameters to connectionpool
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501
# maxsize is the number of requests to host that are allowed in parallel # noqa: E501
# Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501
# cert_reqs
if configuration.verify_ssl:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
# ca_certs
if configuration.ssl_ca_cert:
ca_certs = configuration.ssl_ca_cert
else:
# if not set certificate file, use Mozilla's root certificates.
ca_certs = certifi.where()
addition_pool_args = {}
if configuration.assert_hostname is not None:
addition_pool_args[
"assert_hostname"
] = configuration.assert_hostname # noqa: E501
if maxsize is None:
if configuration.connection_pool_maxsize is not None:
maxsize = configuration.connection_pool_maxsize
else:
maxsize = 4
# https pool manager
if configuration.proxy:
self.pool_manager = urllib3.ProxyManager(
num_pools=pools_size,
maxsize=maxsize,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
cert_file=configuration.cert_file,
key_file=configuration.key_file,
proxy_url=configuration.proxy,
**addition_pool_args
)
else:
self.pool_manager = urllib3.PoolManager(
num_pools=pools_size,
maxsize=maxsize,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
cert_file=configuration.cert_file,
key_file=configuration.key_file,
**addition_pool_args
)
def request(
self,
method,
url,
query_params=None,
headers=None,
body=None,
post_params=None,
_preload_content=True,
_request_timeout=None,
):
"""Perform requests.
:param method: http request method
:param url: http request url
:param query_params: query parameters in the url
:param headers: http request headers
:param body: request json body, for `application/json`
:param post_params: request post parameters,
`application/x-www-form-urlencoded`
and `multipart/form-data`
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
"""
method = method.upper()
assert method in [
"GET",
"HEAD",
"DELETE",
"POST",
"PUT",
"PATCH",
"OPTIONS",
]
if post_params and body:
raise ValueError(
"body parameter cannot be used with post_params parameter."
)
post_params = post_params or {}
headers = headers or {}
timeout = None
if _request_timeout:
if isinstance(
_request_timeout, (int,) if six.PY3 else (int, long)
): # noqa: E501,F821
timeout = urllib3.Timeout(total=_request_timeout)
elif (
isinstance(_request_timeout, tuple)
and len(_request_timeout) == 2
):
timeout = urllib3.Timeout(
connect=_request_timeout[0], read=_request_timeout[1]
)
if "Content-Type" not in headers:
headers["Content-Type"] = "application/json"
try:
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]:
if query_params:
url += "?" + urlencode(query_params)
if re.search("json", headers["Content-Type"], re.IGNORECASE):
request_body = None
if body is not None:
request_body = json.dumps(body)
r = self.pool_manager.request(
method,
url,
body=request_body,
preload_content=_preload_content,
timeout=timeout,
headers=headers,
)
elif (
headers["Content-Type"]
== "application/x-www-form-urlencoded"
): # noqa: E501
r = self.pool_manager.request(
method,
url,
fields=post_params,
encode_multipart=False,
preload_content=_preload_content,
timeout=timeout,
headers=headers,
)
elif headers["Content-Type"] == "multipart/form-data":
# must del headers['Content-Type'], or the correct
# Content-Type which generated by urllib3 will be
# overwritten.
del headers["Content-Type"]
r = self.pool_manager.request(
method,
url,
fields=post_params,
encode_multipart=True,
preload_content=_preload_content,
timeout=timeout,
headers=headers,
)
# Pass a `string` parameter directly in the body to support
# other content types than Json when `body` argument is
# provided in serialized form
elif isinstance(body, str):
request_body = body
r = self.pool_manager.request(
method,
url,
body=request_body,
preload_content=_preload_content,
timeout=timeout,
headers=headers,
)
else:
# Cannot generate the request from given parameters
msg = """Cannot prepare a request message for provided
arguments. Please check that your arguments match
declared content type."""
raise ApiException(status=0, reason=msg)
# For `GET`, `HEAD`
else:
r = self.pool_manager.request(
method,
url,
fields=query_params,
preload_content=_preload_content,
timeout=timeout,
headers=headers,
)
except urllib3.exceptions.SSLError as e:
msg = "{0}\n{1}".format(type(e).__name__, str(e))
raise ApiException(status=0, reason=msg)
if _preload_content:
r = RESTResponse(r)
# In the python 3, the response.data is bytes.
# we need to decode it to string.
if six.PY3:
r.data = r.data.decode("utf8")
# log response body
logger.debug("response body: %s", r.data)
if not 200 <= r.status <= 299:
raise ApiException(http_resp=r)
return r
def GET(
self,
url,
headers=None,
query_params=None,
_preload_content=True,
_request_timeout=None,
):
return self.request(
"GET",
url,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
query_params=query_params,
)
def HEAD(
self,
url,
headers=None,
query_params=None,
_preload_content=True,
_request_timeout=None,
):
return self.request(
"HEAD",
url,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
query_params=query_params,
)
def OPTIONS(
self,
url,
headers=None,
query_params=None,
post_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
):
return self.request(
"OPTIONS",
url,
headers=headers,
query_params=query_params,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
def DELETE(
self,
url,
headers=None,
query_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
):
return self.request(
"DELETE",
url,
headers=headers,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
def POST(
self,
url,
headers=None,
query_params=None,
post_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
):
return self.request(
"POST",
url,
headers=headers,
query_params=query_params,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
def PUT(
self,
url,
headers=None,
query_params=None,
post_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
):
return self.request(
"PUT",
url,
headers=headers,
query_params=query_params,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
def PATCH(
self,
url,
headers=None,
query_params=None,
post_params=None,
body=None,
_preload_content=True,
_request_timeout=None,
):
return self.request(
"PATCH",
url,
headers=headers,
query_params=query_params,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body,
)
class ApiException(Exception):
def __init__(self, status=None, reason=None, http_resp=None):
if http_resp:
self.status = http_resp.status
self.reason = http_resp.reason
self.body = http_resp.data
self.headers = http_resp.getheaders()
else:
self.status = status
self.reason = reason
self.body = None
self.headers = None
def __str__(self):
"""Custom error messages for exception"""
error_message = "({0})\n" "Reason: {1}\n".format(
self.status, self.reason
)
if self.headers:
error_message += "HTTP response headers: {0}\n".format(
self.headers
)
if self.body:
error_message += "HTTP response body: {0}\n".format(self.body)
return error_message
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/rest.py | rest.py |
# coding: utf-8
# flake8: noqa
r"""A Python client for interacting with SRA-compatible Relayers.
0x Protocol is an open standard. Many Relayers opt to implementing a set of
`Standard Relayer API (SRA)
<http://sra-spec.s3-website-us-east-1.amazonaws.com/>`_ endpoints, to make it
easier for anyone to source liquidity that conforms to the 0x order format.
Here, we will show you how you can use the `0x-sra-client`:code: module to
interact with 0x relayers that implement the SRA specification.
Setup
-----
Install the package with pip::
pip install 0x-sra-client
To interact with a 0x Relayer, you need the HTTP endpoint of the Relayer you'd
like to connect to (eg https://api.radarrelay.com/0x/v3).
For testing one can use the `0x-launch-kit-backend
<https://github.com/0xProject/0x-launch-kit-backend#table-of-contents/>`_ to host
orders locally. The examples below assume that this server is running locally
and listening on port 3000, so the Relayer URL they use is
`http://localhost:3000`:code:.
By default, Launch Kit will connect to Kovan via Infura. However, it can be
configured to connect to any JSON-RPC endpoint, on any network. The examples
below assume that Launch Kit is connected to a Ganache development network
accessible at `http://localhost:8545`:code:.
These examples are automatically verified by spinning up docker images
`0xorg/ganache-cli`, `0xorg/mesh`, and `0xorg/launch-kit-backend`. You can
replicate this environment yourself by using `this docker-compose.yml file
<https://github.com/0xProject/0x-monorepo/blob/development/python-packages/sra_client/test/relayer/docker-compose.yml>`_.
(Note: This will only work on Linux, because it uses `network_mode:
"host"`:code:, which only works on Linux.)
Configure and create an API client instance
-------------------------------------------
>>> from zero_ex.sra_client import ApiClient, Configuration, DefaultApi
>>> config = Configuration()
>>> config.host = "http://localhost:3000"
>>> relayer = DefaultApi(ApiClient(config))
Preparing to trade
------------------
Making and taking orders induces the SRA endpoint to deal with the Ethereum
network. Before we can start trading, we need to do a few things with the
network directly.
To start, connect to the Ethereum network:
>>> from web3 import HTTPProvider, Web3
>>> eth_node = HTTPProvider("http://localhost:8545")
For our Maker role, we'll just use the first address available in the node:
>>> maker_address = Web3(eth_node).eth.accounts[0]
The 0x Ganache snapshot loaded into our eth_node has a pre-loaded ZRX balance
for this account, so the example orders below have the maker trading away ZRX.
Before such an order can be valid, though, the maker must give the 0x contracts
permission to trade their ZRX tokens:
>>> from zero_ex.contract_addresses import chain_to_addresses, ChainId
>>> contract_addresses = chain_to_addresses(ChainId(Web3(eth_node).eth.chainId))
>>>
>>> from zero_ex.contract_artifacts import abi_by_name
>>> zrx_token_contract = Web3(eth_node).eth.contract(
... address=Web3.toChecksumAddress(contract_addresses.zrx_token),
... abi=abi_by_name("ZRXToken")
... )
>>>
>>> zrx_token_contract.functions.approve(
... Web3.toChecksumAddress(contract_addresses.erc20_proxy),
... 1000000000000000000
... ).transact(
... {"from": Web3.toChecksumAddress(maker_address)}
... )
HexBytes('0x...')
Post Order
-----------
Post an order for our Maker to trade ZRX for WETH:
>>> from zero_ex.contract_wrappers.exchange.types import Order
>>> from zero_ex.contract_wrappers.order_conversions import order_to_jsdict
>>> from zero_ex.order_utils import (
... asset_data_utils,
... sign_hash)
>>> import random
>>> from datetime import datetime, timedelta
>>> order = Order(
... makerAddress=maker_address,
... takerAddress="0x0000000000000000000000000000000000000000",
... senderAddress="0x0000000000000000000000000000000000000000",
... exchangeAddress=contract_addresses.exchange,
... feeRecipientAddress="0x0000000000000000000000000000000000000000",
... makerAssetData=asset_data_utils.encode_erc20(
... contract_addresses.zrx_token
... ),
... makerFeeAssetData=asset_data_utils.encode_erc20('0x'+'00'*20),
... takerAssetData=asset_data_utils.encode_erc20(
... contract_addresses.ether_token
... ),
... takerFeeAssetData=asset_data_utils.encode_erc20('0x'+'00'*20),
... salt=random.randint(1, 100000000000000000),
... makerFee=0,
... takerFee=0,
... makerAssetAmount=2,
... takerAssetAmount=2,
... expirationTimeSeconds=round(
... (datetime.utcnow() + timedelta(days=1)).timestamp()
... )
... )
>>> from zero_ex.order_utils import generate_order_hash_hex
>>> order_hash_hex = generate_order_hash_hex(
... order, contract_addresses.exchange, Web3(eth_node).eth.chainId
... )
>>> relayer.post_order_with_http_info(
... signed_order_schema=order_to_jsdict(
... order=order,
... exchange_address=contract_addresses.exchange,
... signature=sign_hash(
... eth_node, Web3.toChecksumAddress(maker_address), order_hash_hex
... ),
... chain_id=Web3(eth_node).eth.chainId,
... )
... )[1]
200
Get Order
---------
(But first sleep for a moment, to give the test relayer a chance to start up.
>>> from time import sleep
>>> sleep(0.2)
This is necessary for automated verification of these examples.)
Retrieve the order we just posted:
>>> relayer.get_order("0x" + order_hash_hex)
{'meta_data': {'orderHash': '0x...',
'remainingFillableTakerAssetAmount': '2'},
'order': {'chainId': 1337,
'exchangeAddress': '0x...',
'expirationTimeSeconds': '...',
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetAmount': '2',
'makerAssetData': '0xf47261b0000000000000000000000000...',
'makerFee': '0',
'makerFeeAssetData': '0xf47261b0000000000000000000000000...',
'salt': '...',
'senderAddress': '0x0000000000000000000000000000000000000000',
'signature': '0x...',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': '2',
'takerAssetData': '0xf47261b0000000000000000000000000...',
'takerFee': '0',
'takerFeeAssetData': '0xf47261b0000000000000000000000000...'}}
Get Orders
-----------
Retrieve all of the Relayer's orders, a set which at this point consists solely
of the one we just posted:
>>> relayer.get_orders()
{'records': [{'meta_data': {'orderHash': '0x...',
'remainingFillableTakerAssetAmount': '2'},
'order': {'chainId': 1337,
'exchangeAddress': '0x...',
'expirationTimeSeconds': '...',
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetAmount': '2',
'makerAssetData': '0xf47261b000000000000000000000000...',
'makerFee': '0',
'makerFeeAssetData': '0xf47261b000000000000000000000000...',
'salt': '...',
'senderAddress': '0x0000000000000000000000000000000000000000',
'signature': '0x...',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': '2',
'takerAssetData': '0xf47261b0000000000000000000000000...',
'takerFee': '0',
'takerFeeAssetData': '0xf47261b0000000000000000000000000...'}}...]}
Get Asset Pairs
---------------
Get all of the Relayer's available asset pairs, which here means just WETH and
ZRX, since that's all there is on this Relayer's order book:
>>> relayer.get_asset_pairs()
{'records': [{'assetDataA': {'assetData': '0xf47261b0000000000000000000000000...',
'maxAmount': '115792089237316195423570985008687907853269984665640564039457584007913129639936',
'minAmount': '0',
'precision': 18},
'assetDataB': {'assetData': '0xf47261b0000000000000000000000000...',
'maxAmount': '115792089237316195423570985008687907853269984665640564039457584007913129639936',
'minAmount': '0',
'precision': 18}}]}
>>> asset_data_utils.decode_erc20_asset_data(
... relayer.get_asset_pairs().records[0]['assetDataA']['assetData']
... ).token_address == contract_addresses.zrx_token
True
>>> asset_data_utils.decode_erc20_asset_data(
... relayer.get_asset_pairs().records[0]['assetDataB']['assetData']
... ).token_address == contract_addresses.ether_token
True
Get Orderbook
-------------
Get the Relayer's order book for the WETH/ZRX asset pair (which, again,
consists just of our order):
>>> orderbook = relayer.get_orderbook(
... base_asset_data= "0x" + asset_data_utils.encode_erc20(
... contract_addresses.ether_token
... ).hex(),
... quote_asset_data= "0x" + asset_data_utils.encode_erc20(
... contract_addresses.zrx_token
... ).hex(),
... )
>>> orderbook
{'asks': {'records': [...]},
'bids': {'records': [{'meta_data': {'orderHash': '0x...',
'remainingFillableTakerAssetAmount': '2'},
'order': {'chainId': 1337,
'exchangeAddress': '0x...',
'expirationTimeSeconds': '...',
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetAmount': '2',
'makerAssetData': '0xf47261b0000000000000000000000000...',
'makerFee': '0',
'makerFeeAssetData': '0xf47261b0000000000000000000000000...',
'salt': '...',
'senderAddress': '0x0000000000000000000000000000000000000000',
'signature': '0x...',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': '2',
'takerAssetData': '0xf47261b0000000000000000000000000...',
'takerFee': '0',
'takerFeeAssetData': '0xf47261b0000000000000000000000000...'}}...]}}
Select an order from the orderbook
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
We'll select the order we just submitted, which must be referred to by order
hash. To calculate an order hash, we'll use the Exchange contract:
>>> from zero_ex.contract_wrappers.exchange import Exchange
>>> exchange = Exchange(
... web3_or_provider=eth_node,
... contract_address=chain_to_addresses(ChainId.GANACHE).exchange
... )
>>> from zero_ex.contract_wrappers.order_conversions import jsdict_to_order
>>> order = jsdict_to_order(
... relayer.get_order(
... '0x' + exchange.get_order_info.call(order)["orderHash"].hex()
... ).order
... )
>>> from pprint import pprint
>>> pprint(order)
{'chainId': 1337,
'expirationTimeSeconds': ...,
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetAmount': 2,
'makerAssetData': b...
'makerFee': 0,
'makerFeeAssetData': b...
'salt': ...,
'senderAddress': '0x0000000000000000000000000000000000000000',
'signature': '0x...',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': 2,
'takerAssetData': b...,
'takerFee': 0,
'takerFeeAssetData': b...}
Filling or Cancelling an Order
------------------------------
Fills and cancels are triggered by dealing directly with the 0x Exchange
contract, not by going through a Relayer.
See `the 0x-contract-wrappers documentation
<http://0x-contract-wrappers-py.s3-website-us-east-1.amazonaws.com/>`_ for more
examples.
Filling
^^^^^^^
>>> taker_address = Web3(eth_node).eth.accounts[1]
Our taker will take a ZRX/WETH order, but it doesn't have any WETH yet. By
depositing some ether into the WETH contract, it will be given some WETH to
trade with:
>>> weth_instance = Web3(eth_node).eth.contract(
... address=Web3.toChecksumAddress(contract_addresses.ether_token),
... abi=abi_by_name("WETH9")
... )
>>> weth_instance.functions.deposit().transact(
... {"from": Web3.toChecksumAddress(taker_address),
... "value": 1000000000000000000}
... )
HexBytes('0x...')
Next the taker needs to give the 0x contracts permission to trade their WETH:
>>> weth_instance.functions.approve(
... Web3.toChecksumAddress(contract_addresses.erc20_proxy),
... 1000000000000000000
... ).transact(
... {"from": Web3.toChecksumAddress(taker_address)}
... )
HexBytes('0x...')
Now the taker is ready to trade.
Recall that in a previous example we selected a specific order from the order
book. Now let's have the taker fill it:
>>> from zero_ex.contract_wrappers import TxParams
>>> from zero_ex.order_utils import Order
(Due to `an Issue with the Launch Kit Backend
<https://github.com/0xProject/0x-launch-kit-backend/issues/73>`_, we need to
checksum the address in the order before filling it.)
>>> order['makerAddress'] = Web3.toChecksumAddress(order['makerAddress'])
Finally, filling an order requires paying a protocol fee, which can be sent as
value in the transaction. The calculation of the amount to send is a function
of the gas price, so we need some help from Web3.py for that:
>>> from web3.gas_strategies.rpc import rpc_gas_price_strategy
>>> web3 = Web3(eth_node)
>>> web3.eth.setGasPriceStrategy(rpc_gas_price_strategy)
Before actually executing the fill, it's a good idea to run it as read-only
(non-transactional) so that we can get intelligible errors in case there's
something wrong:
>>> pprint(exchange.fill_order.call(
... order=order,
... taker_asset_fill_amount=order['takerAssetAmount']/2, # note the half fill
... signature=bytes.fromhex(order['signature'].replace('0x', '')),
... tx_params=TxParams(
... from_=taker_address, value=web3.eth.generateGasPrice()*150000,
... ),
... ))
{'makerAssetFilledAmount': 1,
'makerFeePaid': 0,
'protocolFeePaid': ...,
'takerAssetFilledAmount': 1,
'takerFeePaid': 0}
Now we're finally ready to execute the fill:
>>> exchange.fill_order.send_transaction(
... order=order,
... taker_asset_fill_amount=order['takerAssetAmount']/2, # note the half fill
... signature=bytes.fromhex(order['signature'].replace('0x', '')),
... tx_params=TxParams(
... from_=taker_address, value=web3.eth.generateGasPrice()*150000,
... ),
... )
HexBytes('0x...')
Cancelling
^^^^^^^^^^
Note that the above fill was partial: it only filled half of the order. Now
we'll have our maker cancel the remaining order:
>>> exchange.cancel_order.send_transaction(
... order=order,
... tx_params=TxParams(from_=maker_address)
... )
HexBytes('0x...')
""" # noqa: E501 (line too long)
from __future__ import absolute_import
__version__ = "1.0.0"
# import apis into sdk package
from .api.default_api import DefaultApi
# import ApiClient
from .api_client import ApiClient
from .configuration import Configuration
# import models into sdk package
from .models.order_schema import OrderSchema
from .models.paginated_collection_schema import PaginatedCollectionSchema
from .models.relayer_api_asset_data_pairs_response_schema import (
RelayerApiAssetDataPairsResponseSchema,
)
from .models.relayer_api_asset_data_trade_info_schema import (
RelayerApiAssetDataTradeInfoSchema,
)
from .models.relayer_api_error_response_schema import (
RelayerApiErrorResponseSchema,
)
from .models.relayer_api_error_response_schema_validation_errors import (
RelayerApiErrorResponseSchemaValidationErrors,
)
from .models.relayer_api_fee_recipients_response_schema import (
RelayerApiFeeRecipientsResponseSchema,
)
from .models.relayer_api_order_config_payload_schema import (
RelayerApiOrderConfigPayloadSchema,
)
from .models.relayer_api_order_config_response_schema import (
RelayerApiOrderConfigResponseSchema,
)
from .models.relayer_api_order_schema import RelayerApiOrderSchema
from .models.relayer_api_orderbook_response_schema import (
RelayerApiOrderbookResponseSchema,
)
from .models.relayer_api_orders_channel_subscribe_payload_schema import (
RelayerApiOrdersChannelSubscribePayloadSchema,
)
from .models.relayer_api_orders_channel_subscribe_schema import (
RelayerApiOrdersChannelSubscribeSchema,
)
from .models.relayer_api_orders_channel_update_schema import (
RelayerApiOrdersChannelUpdateSchema,
)
from .models.relayer_api_orders_response_schema import (
RelayerApiOrdersResponseSchema,
)
from .models.signed_order_schema import SignedOrderSchema
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/__init__.py | __init__.py |
# coding: utf-8
from __future__ import absolute_import
import copy
import logging
import multiprocessing
import sys
import urllib3
import six
from six.moves import http_client as httplib
class TypeWithDefault(type):
def __init__(cls, name, bases, dct):
super(TypeWithDefault, cls).__init__(name, bases, dct)
cls._default = None
def __call__(cls):
if cls._default is None:
cls._default = type.__call__(cls)
return copy.copy(cls._default)
def set_default(cls, default):
cls._default = copy.copy(default)
class Configuration(six.with_metaclass(TypeWithDefault, object)):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self):
"""Constructor"""
# Default Base url
self.host = "http://localhost:3000"
# Temp file folder for downloading files
self.temp_folder_path = None
# Authentication Settings
# dict to store API key(s)
self.api_key = {}
# dict to store API prefix (e.g. Bearer)
self.api_key_prefix = {}
# Username for HTTP basic authentication
self.username = ""
# Password for HTTP basic authentication
self.password = ""
# Logging Settings
self.logger = {}
self.logger["package_logger"] = logging.getLogger("sra_client")
self.logger["urllib3_logger"] = logging.getLogger("urllib3")
# Log format
self.logger_format = "%(asctime)s %(levelname)s %(message)s"
# Log stream handler
self.logger_stream_handler = None
# Log file handler
self.logger_file_handler = None
# Debug file location
self.logger_file = None
# Debug switch
self.debug = False
# SSL/TLS verification
# Set this to false to skip verifying SSL certificate when calling API
# from https server.
self.verify_ssl = True
# Set this to customize the certificate file to verify the peer.
self.ssl_ca_cert = None
# client certificate file
self.cert_file = None
# client key file
self.key_file = None
# Set this to True/False to enable/disable SSL hostname verification.
self.assert_hostname = None
# urllib3 connection pool's maximum number of connections saved
# per pool. urllib3 uses 1 connection as default value, but this is
# not the best value when you are making a lot of possibly parallel
# requests to the same host, which is often the case here.
# cpu_count * 5 is used as default value to increase performance.
self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
# Proxy URL
self.proxy = None
# Safe chars for path_param
self.safe_chars_for_path_param = ""
@property
def logger_file(self):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
return self.__logger_file
@logger_file.setter
def logger_file(self, value):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
if self.__logger_file:
# If set logging file,
# then add file handler and remove stream handler.
self.logger_file_handler = logging.FileHandler(self.__logger_file)
self.logger_file_handler.setFormatter(self.logger_formatter)
for _, logger in six.iteritems(self.logger):
logger.addHandler(self.logger_file_handler)
@property
def debug(self):
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
return self.__debug
@debug.setter
def debug(self, value):
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
for _, logger in six.iteritems(self.logger):
logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
for _, logger in six.iteritems(self.logger):
logger.setLevel(logging.WARNING)
# turn off httplib debug
httplib.HTTPConnection.debuglevel = 0
@property
def logger_format(self):
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
return self.__logger_format
@logger_format.setter
def logger_format(self, value):
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
self.__logger_format = value
self.logger_formatter = logging.Formatter(self.__logger_format)
def get_api_key_with_prefix(self, identifier):
"""Gets API key (with prefix if set).
:param identifier: The identifier of apiKey.
:return: The token for api key authentication.
"""
if self.api_key.get(identifier) and self.api_key_prefix.get(
identifier
):
return (
self.api_key_prefix[identifier]
+ " "
+ self.api_key[identifier]
) # noqa: E501
elif self.api_key.get(identifier):
return self.api_key[identifier]
def get_basic_auth_token(self):
"""Gets HTTP basic authentication header (string).
:return: The token for basic HTTP authentication.
"""
return urllib3.util.make_headers(
basic_auth=self.username + ":" + self.password
).get("authorization")
def auth_settings(self):
"""Gets Auth Settings dict for api client.
:return: The Auth Settings information dict.
"""
return {}
def to_debug_report(self):
"""Gets the essential information for debugging.
:return: The report for debugging.
"""
return (
"Python SDK Debug Report:\n"
"OS: {env}\n"
"Python Version: {pyversion}\n"
"Version of the API: 2.0.0\n"
"SDK Package Version: 1.0.0".format(
env=sys.platform, pyversion=sys.version
)
)
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/configuration.py | configuration.py |
# coding: utf-8
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from zero_ex.sra_client.api_client import ApiClient
from zero_ex.sra_client.models.relayer_api_order_config_payload_schema import (
RelayerApiOrderConfigPayloadSchema,
)
class DefaultApi(object):
"""Default API for SRA compliant 0x relayers."""
# NOTE: This class is auto generated by OpenAPI Generator
# Ref: https://openapi-generator.tech
# Do not edit the class manually.
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_asset_pairs(self, **kwargs):
"""get_asset_pairs
Retrieves a list of available asset pairs and the information
required to trade them (in any order). Setting only `assetDataA` or
`assetDataB` returns pairs filtered by that asset only.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_asset_pairs(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param str asset_data_a: The assetData value for the first asset in the pair.
:param str asset_data_b: The assetData value for the second asset in the pair.
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiAssetDataPairsResponseSchema`.
If the method is called asynchronously returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_asset_pairs_with_http_info(**kwargs)
else:
(data) = self.get_asset_pairs_with_http_info(**kwargs)
return data
def get_asset_pairs_with_http_info(self, **kwargs):
"""get_asset_pairs
Retrieves a list of available asset pairs and the information
required to trade them (in any order). Setting only `assetDataA` or
`assetDataB` returns pairs filtered by that asset only.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_asset_pairs_with_http_info(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param str asset_data_a: The assetData value for the first asset in the pair.
:param str asset_data_b: The assetData value for the second asset in the pair.
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: A tuple consisting of a
:class:`RelayerApiAssetDataPairsResponseSchema`, an HTTP status
code integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
all_params = [
"asset_data_a",
"asset_data_b",
"page",
"per_page",
]
all_params.append("async_req")
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_asset_pairs" % key
)
local_var_params[key] = val
del local_var_params["kwargs"]
collection_formats = {}
path_params = {}
query_params = []
if "asset_data_a" in local_var_params:
query_params.append(
("assetDataA", local_var_params["asset_data_a"])
)
if "asset_data_b" in local_var_params:
query_params.append(
("assetDataB", local_var_params["asset_data_b"])
)
if "page" in local_var_params:
query_params.append(("page", local_var_params["page"]))
if "per_page" in local_var_params:
query_params.append(("perPage", local_var_params["per_page"]))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
)
# Authentication setting
auth_settings = []
return self.api_client.call_api(
"/v3/asset_pairs",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="RelayerApiAssetDataPairsResponseSchema",
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get(
"_return_http_data_only"
),
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_fee_recipients(self, **kwargs):
"""get_fee_recipients
Retrieves a collection of all fee recipient addresses for a relayer.
This endpoint should be paginated.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_fee_recipients(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiFeeRecipientsResponseSchema`.
If the method is called asynchronously, returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_fee_recipients_with_http_info(**kwargs)
else:
(data) = self.get_fee_recipients_with_http_info(**kwargs)
return data
def get_fee_recipients_with_http_info(self, **kwargs):
"""get_fee_recipients
Retrieves a collection of all fee recipient addresses for a relayer.
This endpoint should be paginated.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_fee_recipients_with_http_info(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: A tuple consisting of a
:class:`RelayerApiFeeRecipientsResponseSchema`, an HTTP status
code integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
all_params = ["page", "per_page"]
all_params.append("async_req")
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_fee_recipients" % key
)
local_var_params[key] = val
del local_var_params["kwargs"]
collection_formats = {}
path_params = {}
query_params = []
if "page" in local_var_params:
query_params.append(("page", local_var_params["page"]))
if "per_page" in local_var_params:
query_params.append(("perPage", local_var_params["per_page"]))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
)
# Authentication setting
auth_settings = []
return self.api_client.call_api(
"/v3/fee_recipients",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="RelayerApiFeeRecipientsResponseSchema",
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get(
"_return_http_data_only"
),
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_order(self, order_hash, **kwargs):
"""get_order
Retrieves the 0x order with meta info that is associated with the hash.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_order(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param str order_hash: The hash of the desired 0x order. (required)
:return: :class:`RelayerApiOrderSchema`.
If the method is called asynchronously, returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_order_with_http_info(order_hash, **kwargs)
else:
(data) = self.get_order_with_http_info(order_hash, **kwargs)
return data
def get_order_with_http_info(self, order_hash, **kwargs):
"""get_order
Retrieves the 0x order with meta info that is associated with the hash.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_order_with_http_info(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param str order_hash: The hash of the desired 0x order. (required)
:return: A tuple consisting of a
:class:`RelayerApiOrderSchema`, an HTTP status code integer, and a
collection of HTTP headers. If the method is called
asynchronously returns the request thread.
"""
local_var_params = locals()
all_params = ["order_hash"]
all_params.append("async_req")
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_order" % key
)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'order_hash' is set
if (
"order_hash" not in local_var_params
or local_var_params["order_hash"] is None
):
raise ValueError(
"Missing the required parameter `order_hash` when calling `get_order`"
)
collection_formats = {}
path_params = {}
if "order_hash" in local_var_params:
path_params["orderHash"] = local_var_params["order_hash"]
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
)
# Authentication setting
auth_settings = []
return self.api_client.call_api(
"/v3/order/{orderHash}",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="RelayerApiOrderSchema",
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get(
"_return_http_data_only"
),
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_order_config(self, **kwargs):
"""get_order_config
Relayers have full discretion over the orders that they are willing
to host on their orderbooks (e.g what fees they charge, etc...). In
order for traders to discover their requirements programmatically,
they can send an incomplete order to this endpoint and receive the
missing fields, specifc to that order. This gives relayers a large
amount of flexibility to tailor fees to unique traders, trading pairs
and volume amounts. Submit a partial order and receive information
required to complete the order: `senderAddress`,
`feeRecipientAddress`, `makerFee`, `takerFee`.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_order_config(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param relayer_api_order_config_payload_schema: instance of
:class:`RelayerApiOrderConfigPayloadSchema`. The fields of a 0x
order the relayer may want to decide what configuration to send
back.
:return: :class:`RelayerApiOrderConfigResponseSchema`.
If the method is called asynchronously returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_order_config_with_http_info(**kwargs)
else:
(data) = self.get_order_config_with_http_info(**kwargs)
return data
def get_order_config_with_http_info(self, **kwargs):
"""get_order_config
Relayers have full discretion over the orders that they are willing
to host on their orderbooks (e.g what fees they charge, etc...). In
order for traders to discover their requirements programmatically,
they can send an incomplete order to this endpoint and receive the
missing fields, specifc to that order. This gives relayers a large
amount of flexibility to tailor fees to unique traders, trading pairs
and volume amounts. Submit a partial order and receive information
required to complete the order: `senderAddress`,
`feeRecipientAddress`, `makerFee`, `takerFee`.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_order_config_with_http_info(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param relayer_api_order_config_payload_schema: instance of
:class: `RelayerApiOrderConfigPayloadSchema`. The fields of a 0x
order the relayer may want to decide what configuration to send
back.
:return: A tuple consisting of a
:class:`RelayerApiOrderConfigResponseSchema`, an HTTP status code
integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
all_params = ["relayer_api_order_config_payload_schema"]
all_params.append("async_req")
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_order_config" % key
)
local_var_params[key] = val
del local_var_params["kwargs"]
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "relayer_api_order_config_payload_schema" in local_var_params:
body_params = local_var_params[
"relayer_api_order_config_payload_schema"
]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
)
# HTTP header `Content-Type`
header_params[
"Content-Type"
] = self.api_client.select_header_content_type(["application/json"])
# Authentication setting
auth_settings = []
return self.api_client.call_api(
"/v3/order_config",
"POST",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="RelayerApiOrderConfigResponseSchema",
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get(
"_return_http_data_only"
),
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_orderbook(self, base_asset_data, quote_asset_data, **kwargs):
"""get_orderbook
Retrieves the orderbook for a given asset pair. This endpoint should
be paginated. Bids will be sorted in
descending order by price, and asks will be sorted in ascending order
by price. Within the price sorted orders, the orders are further
sorted by **taker fee price** which is defined as the **takerFee**
divided by **takerTokenAmount**. After **taker fee price**, orders are
to be sorted by expiration in ascending order. The way pagination
works for this endpoint is that the **page** and **perPage** query
params apply to both `bids` and `asks` collections, and if `page` *
`perPage` = `total` for a certain collection, the `records` for that
collection should just be empty.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_orderbook(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param str base_asset_data: assetData (makerAssetData or
takerAssetData) designated as the base currency in the
`currency pair calculation
<https://en.wikipedia.org/wiki/Currency_pair>`__
of price. (required)
:param str quote_asset_data: assetData (makerAssetData or
takerAssetData) designated as the quote currency in the currency
pair calculation of price. (required)
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiOrderbookResponseSchema`.
If the method is called asynchronously, returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_orderbook_with_http_info(
base_asset_data, quote_asset_data, **kwargs
)
else:
(data) = self.get_orderbook_with_http_info(
base_asset_data, quote_asset_data, **kwargs
)
return data
def get_orderbook_with_http_info(
self, base_asset_data, quote_asset_data, **kwargs
):
"""get_orderbook
Retrieves the orderbook for a given asset pair. This endpoint should
be paginated. Bids will be sorted in
descending order by price, and asks will be sorted in ascending order
by price. Within the price sorted orders, the orders are further
sorted by **taker fee price** which is defined as the **takerFee**
divided by **takerTokenAmount**. After **taker fee price**, orders are
to be sorted by expiration in ascending order. The way pagination
works for this endpoint is that the **page** and **perPage** query
params apply to both `bids` and `asks` collections, and if `page` *
`perPage` = `total` for a certain collection, the `records` for that
collection should just be empty.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_orderbook_with_http_info(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param str base_asset_data: assetData (makerAssetData or
takerAssetData) designated as the base currency in the
`currency pair calculation
<https://en.wikipedia.org/wiki/Currency_pair>`__
of price. (required)
:param str quote_asset_data: assetData (makerAssetData or
takerAssetData) designated as the quote currency in the currency
pair calculation of price. (required)
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: A tuple consisting of a
:class:`RelayerApiOrderbookResponseSchema`, an HTTP status code
integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
all_params = [
"base_asset_data",
"quote_asset_data",
"page",
"per_page",
]
all_params.append("async_req")
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_orderbook" % key
)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'base_asset_data' is set
if (
"base_asset_data" not in local_var_params
or local_var_params["base_asset_data"] is None
):
raise ValueError(
"Missing the required parameter `base_asset_data`"
"when calling `get_orderbook`"
)
# verify the required parameter 'quote_asset_data' is set
if (
"quote_asset_data" not in local_var_params
or local_var_params["quote_asset_data"] is None
):
raise ValueError(
"Missing the required parameter `quote_asset_data`"
" when calling `get_orderbook`"
)
collection_formats = {}
path_params = {}
query_params = []
if "base_asset_data" in local_var_params:
query_params.append(
("baseAssetData", local_var_params["base_asset_data"])
)
if "quote_asset_data" in local_var_params:
query_params.append(
("quoteAssetData", local_var_params["quote_asset_data"])
)
if "page" in local_var_params:
query_params.append(("page", local_var_params["page"]))
if "per_page" in local_var_params:
query_params.append(("perPage", local_var_params["per_page"]))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
)
# Authentication setting
auth_settings = []
return self.api_client.call_api(
"/v3/orderbook",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="RelayerApiOrderbookResponseSchema",
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get(
"_return_http_data_only"
),
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_orders(self, **kwargs):
"""get_orders
Retrieves a list of orders given query parameters. This endpoint
should be paginated. For querying an entire
orderbook snapshot, the orderbook endpoint
is recommended. If both makerAssetData and takerAssetData are
specified, returned orders will be sorted by price determined by
(takerTokenAmount/makerTokenAmount) in ascending order. By default,
orders returned by this endpoint are unsorted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_orders(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param str maker_asset_proxy_id: The maker
`asset proxy id
<https://0x.org/docs/tools/0x.js#enumeration-assetproxyid>`__
(example: "0xf47261b0" for ERC20, "0x02571792" for ERC721).
:param str taker_asset_proxy_id: The taker asset
`asset proxy id
<https://0x.org/docs/tools/0x.js#enumeration-assetproxyid>`__
(example: "0xf47261b0" for ERC20, "0x02571792" for ERC721).
:param str maker_asset_address: The contract address for the maker asset.
:param str taker_asset_address: The contract address for the taker asset.
:param str exchange_address: Contract address for the exchange
contract.
:param str sender_address: Same as senderAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str maker_asset_data: Same as makerAssetData in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str taker_asset_data: Same as takerAssetData in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str trader_asset_data: Same as traderAssetData in the [0x
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str maker_address: Same as makerAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str taker_address: Same as takerAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str trader_address: Same as traderAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str fee_recipient_address: Same as feeRecipientAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiOrdersResponseSchema`.
If the method is called asynchronously, returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.get_orders_with_http_info(**kwargs)
else:
(data) = self.get_orders_with_http_info(**kwargs)
return data
def get_orders_with_http_info(self, **kwargs):
"""get_orders
Retrieves a list of orders given query parameters. This endpoint
should be paginated. For querying an entire
orderbook snapshot, the orderbook endpoint
is recommended. If both makerAssetData and takerAssetData are
specified, returned orders will be sorted by price determined by
(takerTokenAmount/makerTokenAmount) in ascending order. By default,
orders returned by this endpoint are unsorted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.get_orders_with_http_info(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param str maker_asset_proxy_id: The maker
`asset proxy id
<https://0x.org/docs/tools/0x.js#enumeration-assetproxyid>`__
(example: "0xf47261b0" for ERC20, "0x02571792" for ERC721).
:param str taker_asset_proxy_id: The taker asset
`asset proxy id
<https://0x.org/docs/tools/0x.js#enumeration-assetproxyid>`__
(example: "0xf47261b0" for ERC20, "0x02571792" for ERC721).
:param str maker_asset_address: The contract address for the maker asset.
:param str taker_asset_address: The contract address for the taker asset.
:param str exchange_address: Same as exchangeAddress in the [0x
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str sender_address: Same as senderAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str maker_asset_data: Same as makerAssetData in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str taker_asset_data: Same as takerAssetData in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str trader_asset_data: Same as traderAssetData in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str maker_address: Same as makerAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str taker_address: Same as takerAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str trader_address: Same as traderAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param str fee_recipient_address: Same as feeRecipientAddress in the
`0x Protocol v3 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v3/v3-specification.md#order-message-format>`__
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: A tuple consisting of a
:class:`RelayerApiOrdersResponseSchema`, an HTTP status code
integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
all_params = [
"maker_asset_proxy_id",
"taker_asset_proxy_id",
"maker_asset_address",
"taker_asset_address",
"exchange_address",
"sender_address",
"maker_asset_data",
"taker_asset_data",
"trader_asset_data",
"maker_address",
"taker_address",
"trader_address",
"fee_recipient_address",
"page",
"per_page",
]
all_params.append("async_req")
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_orders" % key
)
local_var_params[key] = val
del local_var_params["kwargs"]
collection_formats = {}
path_params = {}
query_params = []
if "maker_asset_proxy_id" in local_var_params:
query_params.append(
("makerAssetProxyId", local_var_params["maker_asset_proxy_id"])
)
if "taker_asset_proxy_id" in local_var_params:
query_params.append(
("takerAssetProxyId", local_var_params["taker_asset_proxy_id"])
)
if "maker_asset_address" in local_var_params:
query_params.append(
("makerAssetAddress", local_var_params["maker_asset_address"])
)
if "taker_asset_address" in local_var_params:
query_params.append(
("takerAssetAddress", local_var_params["taker_asset_address"])
)
if "exchange_address" in local_var_params:
query_params.append(
("exchangeAddress", local_var_params["exchange_address"])
)
if "sender_address" in local_var_params:
query_params.append(
("senderAddress", local_var_params["sender_address"])
)
if "maker_asset_data" in local_var_params:
query_params.append(
("makerAssetData", local_var_params["maker_asset_data"])
)
if "taker_asset_data" in local_var_params:
query_params.append(
("takerAssetData", local_var_params["taker_asset_data"])
)
if "trader_asset_data" in local_var_params:
query_params.append(
("traderAssetData", local_var_params["trader_asset_data"])
)
if "maker_address" in local_var_params:
query_params.append(
("makerAddress", local_var_params["maker_address"])
)
if "taker_address" in local_var_params:
query_params.append(
("takerAddress", local_var_params["taker_address"])
)
if "trader_address" in local_var_params:
query_params.append(
("traderAddress", local_var_params["trader_address"])
)
if "fee_recipient_address" in local_var_params:
query_params.append(
(
"feeRecipientAddress",
local_var_params["fee_recipient_address"],
)
)
if "page" in local_var_params:
query_params.append(("page", local_var_params["page"]))
if "per_page" in local_var_params:
query_params.append(("perPage", local_var_params["per_page"]))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
)
# Authentication setting
auth_settings = []
return self.api_client.call_api(
"/v3/orders",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="RelayerApiOrdersResponseSchema",
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get(
"_return_http_data_only"
),
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def post_order(self, **kwargs):
"""post_order
Submit a signed order to the relayer.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.post_order(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param signed_order_schema: Instance of :class:`SignedOrderSchema`.
A valid signed 0x order based on the schema.
:return: None.
If the method is called asynchronously, returns the request thread.
"""
kwargs["_return_http_data_only"] = True
if kwargs.get("async_req"):
return self.post_order_with_http_info(**kwargs)
else:
(data) = self.post_order_with_http_info(**kwargs)
return data
def post_order_with_http_info(self, **kwargs):
"""post_order
Submit a signed order to the relayer.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass `async_req` = **True**
>>> thread = api.post_order_with_http_info(async_req=True) # doctest: +SKIP
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param signed_order_schema: Instance of :class:`SignedOrderSchema`
A valid signed 0x order based on the schema.
:return: A tuple consisting of the response data (always empty for this
method), an HTTP status code integer, and a collection of HTTP
headers. If the method is called asynchronously returns the
request thread.
"""
local_var_params = locals()
all_params = ["signed_order_schema"]
all_params.append("async_req")
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method post_order" % key
)
local_var_params[key] = val
del local_var_params["kwargs"]
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "signed_order_schema" in local_var_params:
body_params = local_var_params["signed_order_schema"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
)
# HTTP header `Content-Type`
header_params[
"Content-Type"
] = self.api_client.select_header_content_type(["application/json"])
# Authentication setting
auth_settings = []
return self.api_client.call_api(
"/v3/order",
"POST",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get(
"_return_http_data_only"
),
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/api/default_api.py | default_api.py |
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from zero_ex.sra_client.api.default_api import DefaultApi
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/api/__init__.py | __init__.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class OrderSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {}
attribute_map = {
"maker_address": "makerAddress",
"taker_address": "takerAddress",
"maker_fee": "makerFee",
"taker_fee": "takerFee",
"sender_address": "senderAddress",
"maker_asset_amount": "makerAssetAmount",
"taker_asset_amount": "takerAssetAmount",
"maker_asset_data": "makerAssetData",
"taker_asset_data": "takerAssetData",
"salt": "salt",
"exchange_address": "exchangeAddress",
"fee_recipient_address": "feeRecipientAddress",
"expiration_time_seconds": "expirationTimeSeconds",
}
def __init__(
self,
maker_address=None,
taker_address=None,
maker_fee=None,
taker_fee=None,
sender_address=None,
maker_asset_amount=None,
taker_asset_amount=None,
maker_asset_data=None,
taker_asset_data=None,
salt=None,
exchange_address=None,
fee_recipient_address=None,
expiration_time_seconds=None,
): # noqa: E501
"""OrderSchema - a model defined in OpenAPI""" # noqa: E501
self._maker_address = None
self._taker_address = None
self._maker_fee = None
self._taker_fee = None
self._sender_address = None
self._maker_asset_amount = None
self._taker_asset_amount = None
self._maker_asset_data = None
self._taker_asset_data = None
self._salt = None
self._exchange_address = None
self._fee_recipient_address = None
self._expiration_time_seconds = None
self.discriminator = None
self.maker_address = maker_address
self.taker_address = taker_address
self.maker_fee = maker_fee
self.taker_fee = taker_fee
self.sender_address = sender_address
self.maker_asset_amount = maker_asset_amount
self.taker_asset_amount = taker_asset_amount
self.maker_asset_data = maker_asset_data
self.taker_asset_data = taker_asset_data
self.salt = salt
self.exchange_address = exchange_address
self.fee_recipient_address = fee_recipient_address
self.expiration_time_seconds = expiration_time_seconds
@property
def maker_address(self):
"""Gets the maker_address of this OrderSchema. # noqa: E501
:return: The maker_address of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._maker_address
@maker_address.setter
def maker_address(self, maker_address):
"""Sets the maker_address of this OrderSchema.
:param maker_address: The maker_address of this OrderSchema. # noqa: E501
:type: str
"""
if maker_address is None:
raise ValueError(
"Invalid value for `maker_address`, must not be `None`"
) # noqa: E501
if maker_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", maker_address
): # noqa: E501
raise ValueError(
r"Invalid value for `maker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._maker_address = maker_address
@property
def taker_address(self):
"""Gets the taker_address of this OrderSchema. # noqa: E501
:return: The taker_address of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._taker_address
@taker_address.setter
def taker_address(self, taker_address):
"""Sets the taker_address of this OrderSchema.
:param taker_address: The taker_address of this OrderSchema. # noqa: E501
:type: str
"""
if taker_address is None:
raise ValueError(
"Invalid value for `taker_address`, must not be `None`"
) # noqa: E501
if taker_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", taker_address
): # noqa: E501
raise ValueError(
r"Invalid value for `taker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._taker_address = taker_address
@property
def maker_fee(self):
"""Gets the maker_fee of this OrderSchema. # noqa: E501
:return: The maker_fee of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._maker_fee
@maker_fee.setter
def maker_fee(self, maker_fee):
"""Sets the maker_fee of this OrderSchema.
:param maker_fee: The maker_fee of this OrderSchema. # noqa: E501
:type: str
"""
if maker_fee is None:
raise ValueError(
"Invalid value for `maker_fee`, must not be `None`"
) # noqa: E501
if maker_fee is not None and not re.search(
r"^\d+$", maker_fee
): # noqa: E501
raise ValueError(
r"Invalid value for `maker_fee`, must be a follow pattern or equal to `/^\d+$/`"
) # noqa: E501
self._maker_fee = maker_fee
@property
def taker_fee(self):
"""Gets the taker_fee of this OrderSchema. # noqa: E501
:return: The taker_fee of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._taker_fee
@taker_fee.setter
def taker_fee(self, taker_fee):
"""Sets the taker_fee of this OrderSchema.
:param taker_fee: The taker_fee of this OrderSchema. # noqa: E501
:type: str
"""
if taker_fee is None:
raise ValueError(
"Invalid value for `taker_fee`, must not be `None`"
) # noqa: E501
if taker_fee is not None and not re.search(
r"^\d+$", taker_fee
): # noqa: E501
raise ValueError(
r"Invalid value for `taker_fee`, must be a follow pattern or equal to `/^\d+$/`"
) # noqa: E501
self._taker_fee = taker_fee
@property
def sender_address(self):
"""Gets the sender_address of this OrderSchema. # noqa: E501
:return: The sender_address of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._sender_address
@sender_address.setter
def sender_address(self, sender_address):
"""Sets the sender_address of this OrderSchema.
:param sender_address: The sender_address of this OrderSchema. # noqa: E501
:type: str
"""
if sender_address is None:
raise ValueError(
"Invalid value for `sender_address`, must not be `None`"
) # noqa: E501
if sender_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", sender_address
): # noqa: E501
raise ValueError(
r"Invalid value for `sender_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._sender_address = sender_address
@property
def maker_asset_amount(self):
"""Gets the maker_asset_amount of this OrderSchema. # noqa: E501
:return: The maker_asset_amount of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._maker_asset_amount
@maker_asset_amount.setter
def maker_asset_amount(self, maker_asset_amount):
"""Sets the maker_asset_amount of this OrderSchema.
:param maker_asset_amount: The maker_asset_amount of this OrderSchema. # noqa: E501
:type: str
"""
if maker_asset_amount is None:
raise ValueError(
"Invalid value for `maker_asset_amount`, must not be `None`"
) # noqa: E501
if maker_asset_amount is not None and not re.search(
r"^\d+$", maker_asset_amount
): # noqa: E501
raise ValueError(
r"Invalid value for `maker_asset_amount`, must be a follow pattern or equal to `/^\d+$/`"
) # noqa: E501
self._maker_asset_amount = maker_asset_amount
@property
def taker_asset_amount(self):
"""Gets the taker_asset_amount of this OrderSchema. # noqa: E501
:return: The taker_asset_amount of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._taker_asset_amount
@taker_asset_amount.setter
def taker_asset_amount(self, taker_asset_amount):
"""Sets the taker_asset_amount of this OrderSchema.
:param taker_asset_amount: The taker_asset_amount of this OrderSchema. # noqa: E501
:type: str
"""
if taker_asset_amount is None:
raise ValueError(
"Invalid value for `taker_asset_amount`, must not be `None`"
) # noqa: E501
if taker_asset_amount is not None and not re.search(
r"^\d+$", taker_asset_amount
): # noqa: E501
raise ValueError(
r"Invalid value for `taker_asset_amount`, must be a follow pattern or equal to `/^\d+$/`"
) # noqa: E501
self._taker_asset_amount = taker_asset_amount
@property
def maker_asset_data(self):
"""Gets the maker_asset_data of this OrderSchema. # noqa: E501
:return: The maker_asset_data of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._maker_asset_data
@maker_asset_data.setter
def maker_asset_data(self, maker_asset_data):
"""Sets the maker_asset_data of this OrderSchema.
:param maker_asset_data: The maker_asset_data of this OrderSchema. # noqa: E501
:type: str
"""
if maker_asset_data is None:
raise ValueError(
"Invalid value for `maker_asset_data`, must not be `None`"
) # noqa: E501
if maker_asset_data is not None and not re.search(
r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data
): # noqa: E501
raise ValueError(
r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`"
) # noqa: E501
self._maker_asset_data = maker_asset_data
@property
def taker_asset_data(self):
"""Gets the taker_asset_data of this OrderSchema. # noqa: E501
:return: The taker_asset_data of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._taker_asset_data
@taker_asset_data.setter
def taker_asset_data(self, taker_asset_data):
"""Sets the taker_asset_data of this OrderSchema.
:param taker_asset_data: The taker_asset_data of this OrderSchema. # noqa: E501
:type: str
"""
if taker_asset_data is None:
raise ValueError(
"Invalid value for `taker_asset_data`, must not be `None`"
) # noqa: E501
if taker_asset_data is not None and not re.search(
r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data
): # noqa: E501
raise ValueError(
r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`"
) # noqa: E501
self._taker_asset_data = taker_asset_data
@property
def salt(self):
"""Gets the salt of this OrderSchema. # noqa: E501
:return: The salt of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._salt
@salt.setter
def salt(self, salt):
"""Sets the salt of this OrderSchema.
:param salt: The salt of this OrderSchema. # noqa: E501
:type: str
"""
if salt is None:
raise ValueError(
"Invalid value for `salt`, must not be `None`"
) # noqa: E501
if salt is not None and not re.search(r"^\d+$", salt): # noqa: E501
raise ValueError(
r"Invalid value for `salt`, must be a follow pattern or equal to `/^\d+$/`"
) # noqa: E501
self._salt = salt
@property
def exchange_address(self):
"""Gets the exchange_address of this OrderSchema. # noqa: E501
:return: The exchange_address of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._exchange_address
@exchange_address.setter
def exchange_address(self, exchange_address):
"""Sets the exchange_address of this OrderSchema.
:param exchange_address: The exchange_address of this OrderSchema. # noqa: E501
:type: str
"""
if exchange_address is None:
raise ValueError(
"Invalid value for `exchange_address`, must not be `None`"
) # noqa: E501
if exchange_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", exchange_address
): # noqa: E501
raise ValueError(
r"Invalid value for `exchange_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._exchange_address = exchange_address
@property
def fee_recipient_address(self):
"""Gets the fee_recipient_address of this OrderSchema. # noqa: E501
:return: The fee_recipient_address of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._fee_recipient_address
@fee_recipient_address.setter
def fee_recipient_address(self, fee_recipient_address):
"""Sets the fee_recipient_address of this OrderSchema.
:param fee_recipient_address: The fee_recipient_address of this OrderSchema. # noqa: E501
:type: str
"""
if fee_recipient_address is None:
raise ValueError(
"Invalid value for `fee_recipient_address`, must not be `None`"
) # noqa: E501
if fee_recipient_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", fee_recipient_address
): # noqa: E501
raise ValueError(
r"Invalid value for `fee_recipient_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._fee_recipient_address = fee_recipient_address
@property
def expiration_time_seconds(self):
"""Gets the expiration_time_seconds of this OrderSchema. # noqa: E501
:return: The expiration_time_seconds of this OrderSchema. # noqa: E501
:rtype: str
"""
return self._expiration_time_seconds
@expiration_time_seconds.setter
def expiration_time_seconds(self, expiration_time_seconds):
"""Sets the expiration_time_seconds of this OrderSchema.
:param expiration_time_seconds: The expiration_time_seconds of this OrderSchema. # noqa: E501
:type: str
"""
if expiration_time_seconds is None:
raise ValueError(
"Invalid value for `expiration_time_seconds`, must not be `None`"
) # noqa: E501
if expiration_time_seconds is not None and not re.search(
r"^\d+$", expiration_time_seconds
): # noqa: E501
raise ValueError(
r"Invalid value for `expiration_time_seconds`, must be a follow pattern or equal to `/^\d+$/`"
) # noqa: E501
self._expiration_time_seconds = expiration_time_seconds
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, OrderSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/order_schema.py | order_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiErrorResponseSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"code": "int",
"reason": "str",
"validation_errors": "list[RelayerApiErrorResponseSchemaValidationErrors]",
}
attribute_map = {
"code": "code",
"reason": "reason",
"validation_errors": "validationErrors",
}
def __init__(
self, code=None, reason=None, validation_errors=None
): # noqa: E501
"""RelayerApiErrorResponseSchema - a model defined in OpenAPI""" # noqa: E501
self._code = None
self._reason = None
self._validation_errors = None
self.discriminator = None
self.code = code
self.reason = reason
if validation_errors is not None:
self.validation_errors = validation_errors
@property
def code(self):
"""Gets the code of this RelayerApiErrorResponseSchema. # noqa: E501
:return: The code of this RelayerApiErrorResponseSchema. # noqa: E501
:rtype: int
"""
return self._code
@code.setter
def code(self, code):
"""Sets the code of this RelayerApiErrorResponseSchema.
:param code: The code of this RelayerApiErrorResponseSchema. # noqa: E501
:type: int
"""
if code is None:
raise ValueError(
"Invalid value for `code`, must not be `None`"
) # noqa: E501
if code is not None and code > 103: # noqa: E501
raise ValueError(
"Invalid value for `code`, must be a value less than or equal to `103`"
) # noqa: E501
if code is not None and code < 100: # noqa: E501
raise ValueError(
"Invalid value for `code`, must be a value greater than or equal to `100`"
) # noqa: E501
self._code = code
@property
def reason(self):
"""Gets the reason of this RelayerApiErrorResponseSchema. # noqa: E501
:return: The reason of this RelayerApiErrorResponseSchema. # noqa: E501
:rtype: str
"""
return self._reason
@reason.setter
def reason(self, reason):
"""Sets the reason of this RelayerApiErrorResponseSchema.
:param reason: The reason of this RelayerApiErrorResponseSchema. # noqa: E501
:type: str
"""
if reason is None:
raise ValueError(
"Invalid value for `reason`, must not be `None`"
) # noqa: E501
self._reason = reason
@property
def validation_errors(self):
"""Gets the validation_errors of this RelayerApiErrorResponseSchema. # noqa: E501
:return: The validation_errors of this RelayerApiErrorResponseSchema. # noqa: E501
:rtype: list[RelayerApiErrorResponseSchemaValidationErrors]
"""
return self._validation_errors
@validation_errors.setter
def validation_errors(self, validation_errors):
"""Sets the validation_errors of this RelayerApiErrorResponseSchema.
:param validation_errors: The validation_errors of this RelayerApiErrorResponseSchema. # noqa: E501
:type: list[RelayerApiErrorResponseSchemaValidationErrors]
"""
self._validation_errors = validation_errors
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RelayerApiErrorResponseSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_error_response_schema.py | relayer_api_error_response_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiOrderConfigPayloadSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"maker_address": "str",
"taker_address": "str",
"maker_asset_amount": "str",
"taker_asset_amount": "str",
"maker_asset_data": "str",
"taker_asset_data": "str",
"exchange_address": "str",
"expiration_time_seconds": "str",
}
attribute_map = {
"maker_address": "makerAddress",
"taker_address": "takerAddress",
"maker_asset_amount": "makerAssetAmount",
"taker_asset_amount": "takerAssetAmount",
"maker_asset_data": "makerAssetData",
"taker_asset_data": "takerAssetData",
"exchange_address": "exchangeAddress",
"expiration_time_seconds": "expirationTimeSeconds",
}
def __init__(
self,
maker_address=None,
taker_address=None,
maker_asset_amount=None,
taker_asset_amount=None,
maker_asset_data=None,
taker_asset_data=None,
exchange_address=None,
expiration_time_seconds=None,
): # noqa: E501
"""RelayerApiOrderConfigPayloadSchema - a model defined in OpenAPI""" # noqa: E501
self._maker_address = None
self._taker_address = None
self._maker_asset_amount = None
self._taker_asset_amount = None
self._maker_asset_data = None
self._taker_asset_data = None
self._exchange_address = None
self._expiration_time_seconds = None
self.discriminator = None
self.maker_address = maker_address
self.taker_address = taker_address
self.maker_asset_amount = maker_asset_amount
self.taker_asset_amount = taker_asset_amount
self.maker_asset_data = maker_asset_data
self.taker_asset_data = taker_asset_data
self.exchange_address = exchange_address
self.expiration_time_seconds = expiration_time_seconds
@property
def maker_address(self):
"""Gets the maker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:return: The maker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:rtype: str
"""
return self._maker_address
@maker_address.setter
def maker_address(self, maker_address):
"""Sets the maker_address of this RelayerApiOrderConfigPayloadSchema.
:param maker_address: The maker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:type: str
"""
if maker_address is None:
raise ValueError(
"Invalid value for `maker_address`, must not be `None`"
) # noqa: E501
if maker_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", maker_address
): # noqa: E501
raise ValueError(
r"Invalid value for `maker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._maker_address = maker_address
@property
def taker_address(self):
"""Gets the taker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:return: The taker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:rtype: str
"""
return self._taker_address
@taker_address.setter
def taker_address(self, taker_address):
"""Sets the taker_address of this RelayerApiOrderConfigPayloadSchema.
:param taker_address: The taker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:type: str
"""
if taker_address is None:
raise ValueError(
"Invalid value for `taker_address`, must not be `None`"
) # noqa: E501
if taker_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", taker_address
): # noqa: E501
raise ValueError(
r"Invalid value for `taker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._taker_address = taker_address
@property
def maker_asset_amount(self):
"""Gets the maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:return: The maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:rtype: str
"""
return self._maker_asset_amount
@maker_asset_amount.setter
def maker_asset_amount(self, maker_asset_amount):
"""Sets the maker_asset_amount of this RelayerApiOrderConfigPayloadSchema.
:param maker_asset_amount: The maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:type: str
"""
if maker_asset_amount is None:
raise ValueError(
"Invalid value for `maker_asset_amount`, must not be `None`"
) # noqa: E501
if maker_asset_amount is not None and not re.search(
r"^\\d+$", maker_asset_amount
): # noqa: E501
raise ValueError(
r"Invalid value for `maker_asset_amount`, must be a follow pattern or equal to `/^\\d+$/`"
) # noqa: E501
self._maker_asset_amount = maker_asset_amount
@property
def taker_asset_amount(self):
"""Gets the taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:return: The taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:rtype: str
"""
return self._taker_asset_amount
@taker_asset_amount.setter
def taker_asset_amount(self, taker_asset_amount):
"""Sets the taker_asset_amount of this RelayerApiOrderConfigPayloadSchema.
:param taker_asset_amount: The taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:type: str
"""
if taker_asset_amount is None:
raise ValueError(
"Invalid value for `taker_asset_amount`, must not be `None`"
) # noqa: E501
if taker_asset_amount is not None and not re.search(
r"^\\d+$", taker_asset_amount
): # noqa: E501
raise ValueError(
r"Invalid value for `taker_asset_amount`, must be a follow pattern or equal to `/^\\d+$/`"
) # noqa: E501
self._taker_asset_amount = taker_asset_amount
@property
def maker_asset_data(self):
"""Gets the maker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:return: The maker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:rtype: str
"""
return self._maker_asset_data
@maker_asset_data.setter
def maker_asset_data(self, maker_asset_data):
"""Sets the maker_asset_data of this RelayerApiOrderConfigPayloadSchema.
:param maker_asset_data: The maker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:type: str
"""
if maker_asset_data is None:
raise ValueError(
"Invalid value for `maker_asset_data`, must not be `None`"
) # noqa: E501
if maker_asset_data is not None and not re.search(
r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data
): # noqa: E501
raise ValueError(
r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`"
) # noqa: E501
self._maker_asset_data = maker_asset_data
@property
def taker_asset_data(self):
"""Gets the taker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:return: The taker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:rtype: str
"""
return self._taker_asset_data
@taker_asset_data.setter
def taker_asset_data(self, taker_asset_data):
"""Sets the taker_asset_data of this RelayerApiOrderConfigPayloadSchema.
:param taker_asset_data: The taker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:type: str
"""
if taker_asset_data is None:
raise ValueError(
"Invalid value for `taker_asset_data`, must not be `None`"
) # noqa: E501
if taker_asset_data is not None and not re.search(
r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data
): # noqa: E501
raise ValueError(
r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`"
) # noqa: E501
self._taker_asset_data = taker_asset_data
@property
def exchange_address(self):
"""Gets the exchange_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:return: The exchange_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:rtype: str
"""
return self._exchange_address
@exchange_address.setter
def exchange_address(self, exchange_address):
"""Sets the exchange_address of this RelayerApiOrderConfigPayloadSchema.
:param exchange_address: The exchange_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:type: str
"""
if exchange_address is None:
raise ValueError(
"Invalid value for `exchange_address`, must not be `None`"
) # noqa: E501
if exchange_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", exchange_address
): # noqa: E501
raise ValueError(
r"Invalid value for `exchange_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._exchange_address = exchange_address
@property
def expiration_time_seconds(self):
"""Gets the expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:return: The expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:rtype: str
"""
return self._expiration_time_seconds
@expiration_time_seconds.setter
def expiration_time_seconds(self, expiration_time_seconds):
"""Sets the expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema.
:param expiration_time_seconds: The expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. # noqa: E501
:type: str
"""
if expiration_time_seconds is None:
raise ValueError(
"Invalid value for `expiration_time_seconds`, must not be `None`"
) # noqa: E501
if expiration_time_seconds is not None and not re.search(
r"^\\d+$", expiration_time_seconds
): # noqa: E501
raise ValueError(
r"Invalid value for `expiration_time_seconds`, must be a follow pattern or equal to `/^\\d+$/`"
) # noqa: E501
self._expiration_time_seconds = expiration_time_seconds
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RelayerApiOrderConfigPayloadSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_order_config_payload_schema.py | relayer_api_order_config_payload_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiOrderConfigResponseSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"maker_fee": "str",
"taker_fee": "str",
"fee_recipient_address": "str",
"sender_address": "str",
}
attribute_map = {
"maker_fee": "makerFee",
"taker_fee": "takerFee",
"fee_recipient_address": "feeRecipientAddress",
"sender_address": "senderAddress",
}
def __init__(
self,
maker_fee=None,
taker_fee=None,
fee_recipient_address=None,
sender_address=None,
): # noqa: E501
"""RelayerApiOrderConfigResponseSchema - a model defined in OpenAPI""" # noqa: E501
self._maker_fee = None
self._taker_fee = None
self._fee_recipient_address = None
self._sender_address = None
self.discriminator = None
self.maker_fee = maker_fee
self.taker_fee = taker_fee
self.fee_recipient_address = fee_recipient_address
self.sender_address = sender_address
@property
def maker_fee(self):
"""Gets the maker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:return: The maker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:rtype: str
"""
return self._maker_fee
@maker_fee.setter
def maker_fee(self, maker_fee):
"""Sets the maker_fee of this RelayerApiOrderConfigResponseSchema.
:param maker_fee: The maker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:type: str
"""
if maker_fee is None:
raise ValueError(
"Invalid value for `maker_fee`, must not be `None`"
) # noqa: E501
if maker_fee is not None and not re.search(
r"^\\d+$", maker_fee
): # noqa: E501
raise ValueError(
r"Invalid value for `maker_fee`, must be a follow pattern or equal to `/^\\d+$/`"
) # noqa: E501
self._maker_fee = maker_fee
@property
def taker_fee(self):
"""Gets the taker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:return: The taker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:rtype: str
"""
return self._taker_fee
@taker_fee.setter
def taker_fee(self, taker_fee):
"""Sets the taker_fee of this RelayerApiOrderConfigResponseSchema.
:param taker_fee: The taker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:type: str
"""
if taker_fee is None:
raise ValueError(
"Invalid value for `taker_fee`, must not be `None`"
) # noqa: E501
if taker_fee is not None and not re.search(
r"^\\d+$", taker_fee
): # noqa: E501
raise ValueError(
r"Invalid value for `taker_fee`, must be a follow pattern or equal to `/^\\d+$/`"
) # noqa: E501
self._taker_fee = taker_fee
@property
def fee_recipient_address(self):
"""Gets the fee_recipient_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:return: The fee_recipient_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:rtype: str
"""
return self._fee_recipient_address
@fee_recipient_address.setter
def fee_recipient_address(self, fee_recipient_address):
"""Sets the fee_recipient_address of this RelayerApiOrderConfigResponseSchema.
:param fee_recipient_address: The fee_recipient_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:type: str
"""
if fee_recipient_address is None:
raise ValueError(
"Invalid value for `fee_recipient_address`, must not be `None`"
) # noqa: E501
if fee_recipient_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", fee_recipient_address
): # noqa: E501
raise ValueError(
r"Invalid value for `fee_recipient_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._fee_recipient_address = fee_recipient_address
@property
def sender_address(self):
"""Gets the sender_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:return: The sender_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:rtype: str
"""
return self._sender_address
@sender_address.setter
def sender_address(self, sender_address):
"""Sets the sender_address of this RelayerApiOrderConfigResponseSchema.
:param sender_address: The sender_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501
:type: str
"""
if sender_address is None:
raise ValueError(
"Invalid value for `sender_address`, must not be `None`"
) # noqa: E501
if sender_address is not None and not re.search(
r"^0x[0-9a-f]{40}$", sender_address
): # noqa: E501
raise ValueError(
r"Invalid value for `sender_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`"
) # noqa: E501
self._sender_address = sender_address
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RelayerApiOrderConfigResponseSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_order_config_response_schema.py | relayer_api_order_config_response_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiFeeRecipientsResponseSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {"records": "list[str]"}
attribute_map = {"records": "records"}
def __init__(self, records=None): # noqa: E501
"""RelayerApiFeeRecipientsResponseSchema - a model defined in OpenAPI""" # noqa: E501
self._records = None
self.discriminator = None
self.records = records
@property
def records(self):
"""Gets the records of this RelayerApiFeeRecipientsResponseSchema. # noqa: E501
:return: The records of this RelayerApiFeeRecipientsResponseSchema. # noqa: E501
:rtype: list[str]
"""
return self._records
@records.setter
def records(self, records):
"""Sets the records of this RelayerApiFeeRecipientsResponseSchema.
:param records: The records of this RelayerApiFeeRecipientsResponseSchema. # noqa: E501
:type: list[str]
"""
if records is None:
raise ValueError(
"Invalid value for `records`, must not be `None`"
) # noqa: E501
self._records = records
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RelayerApiFeeRecipientsResponseSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_fee_recipients_response_schema.py | relayer_api_fee_recipients_response_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiOrderSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {"order": "OrderSchema", "meta_data": "object"}
attribute_map = {"order": "order", "meta_data": "metaData"}
def __init__(self, order=None, meta_data=None): # noqa: E501
"""RelayerApiOrderSchema - a model defined in OpenAPI""" # noqa: E501
self._order = None
self._meta_data = None
self.discriminator = None
self.order = order
self.meta_data = meta_data
@property
def order(self):
"""Gets the order of this RelayerApiOrderSchema. # noqa: E501
:return: The order of this RelayerApiOrderSchema. # noqa: E501
:rtype: OrderSchema
"""
return self._order
@order.setter
def order(self, order):
"""Sets the order of this RelayerApiOrderSchema.
:param order: The order of this RelayerApiOrderSchema. # noqa: E501
:type: OrderSchema
"""
if order is None:
raise ValueError(
"Invalid value for `order`, must not be `None`"
) # noqa: E501
self._order = order
@property
def meta_data(self):
"""Gets the meta_data of this RelayerApiOrderSchema. # noqa: E501
:return: The meta_data of this RelayerApiOrderSchema. # noqa: E501
:rtype: object
"""
return self._meta_data
@meta_data.setter
def meta_data(self, meta_data):
"""Sets the meta_data of this RelayerApiOrderSchema.
:param meta_data: The meta_data of this RelayerApiOrderSchema. # noqa: E501
:type: object
"""
if meta_data is None:
raise ValueError(
"Invalid value for `meta_data`, must not be `None`"
) # noqa: E501
self._meta_data = meta_data
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RelayerApiOrderSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_order_schema.py | relayer_api_order_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiOrderbookResponseSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"bids": "RelayerApiOrdersResponseSchema",
"asks": "RelayerApiOrdersResponseSchema",
}
attribute_map = {"bids": "bids", "asks": "asks"}
def __init__(self, bids=None, asks=None): # noqa: E501
"""RelayerApiOrderbookResponseSchema - a model defined in OpenAPI""" # noqa: E501
self._bids = None
self._asks = None
self.discriminator = None
self.bids = bids
self.asks = asks
@property
def bids(self):
"""Gets the bids of this RelayerApiOrderbookResponseSchema. # noqa: E501
:return: The bids of this RelayerApiOrderbookResponseSchema. # noqa: E501
:rtype: RelayerApiOrdersResponseSchema
"""
return self._bids
@bids.setter
def bids(self, bids):
"""Sets the bids of this RelayerApiOrderbookResponseSchema.
:param bids: The bids of this RelayerApiOrderbookResponseSchema. # noqa: E501
:type: RelayerApiOrdersResponseSchema
"""
if bids is None:
raise ValueError(
"Invalid value for `bids`, must not be `None`"
) # noqa: E501
self._bids = bids
@property
def asks(self):
"""Gets the asks of this RelayerApiOrderbookResponseSchema. # noqa: E501
:return: The asks of this RelayerApiOrderbookResponseSchema. # noqa: E501
:rtype: RelayerApiOrdersResponseSchema
"""
return self._asks
@asks.setter
def asks(self, asks):
"""Sets the asks of this RelayerApiOrderbookResponseSchema.
:param asks: The asks of this RelayerApiOrderbookResponseSchema. # noqa: E501
:type: RelayerApiOrdersResponseSchema
"""
if asks is None:
raise ValueError(
"Invalid value for `asks`, must not be `None`"
) # noqa: E501
self._asks = asks
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RelayerApiOrderbookResponseSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_orderbook_response_schema.py | relayer_api_orderbook_response_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiOrdersChannelUpdateSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"type": "str",
"channel": "str",
"request_id": "str",
"payload": "list[RelayerApiOrderSchema]",
}
attribute_map = {
"type": "type",
"channel": "channel",
"request_id": "requestId",
"payload": "payload",
}
def __init__(
self, type=None, channel=None, request_id=None, payload=None
): # noqa: E501
"""RelayerApiOrdersChannelUpdateSchema - a model defined in OpenAPI""" # noqa: E501
self._type = None
self._channel = None
self._request_id = None
self._payload = None
self.discriminator = None
self.type = type
self.channel = channel
self.request_id = request_id
if payload is not None:
self.payload = payload
@property
def type(self):
"""Gets the type of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:return: The type of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this RelayerApiOrdersChannelUpdateSchema.
:param type: The type of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:type: str
"""
if type is None:
raise ValueError(
"Invalid value for `type`, must not be `None`"
) # noqa: E501
allowed_values = ["update"] # noqa: E501
if type not in allowed_values:
raise ValueError(
"Invalid value for `type` ({0}), must be one of {1}".format( # noqa: E501
type, allowed_values
)
)
self._type = type
@property
def channel(self):
"""Gets the channel of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:return: The channel of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:rtype: str
"""
return self._channel
@channel.setter
def channel(self, channel):
"""Sets the channel of this RelayerApiOrdersChannelUpdateSchema.
:param channel: The channel of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:type: str
"""
if channel is None:
raise ValueError(
"Invalid value for `channel`, must not be `None`"
) # noqa: E501
allowed_values = ["orders"] # noqa: E501
if channel not in allowed_values:
raise ValueError(
"Invalid value for `channel` ({0}), must be one of {1}".format( # noqa: E501
channel, allowed_values
)
)
self._channel = channel
@property
def request_id(self):
"""Gets the request_id of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:return: The request_id of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:rtype: str
"""
return self._request_id
@request_id.setter
def request_id(self, request_id):
"""Sets the request_id of this RelayerApiOrdersChannelUpdateSchema.
:param request_id: The request_id of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:type: str
"""
if request_id is None:
raise ValueError(
"Invalid value for `request_id`, must not be `None`"
) # noqa: E501
self._request_id = request_id
@property
def payload(self):
"""Gets the payload of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:return: The payload of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:rtype: list[RelayerApiOrderSchema]
"""
return self._payload
@payload.setter
def payload(self, payload):
"""Sets the payload of this RelayerApiOrdersChannelUpdateSchema.
:param payload: The payload of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501
:type: list[RelayerApiOrderSchema]
"""
self._payload = payload
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RelayerApiOrdersChannelUpdateSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_orders_channel_update_schema.py | relayer_api_orders_channel_update_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiAssetDataTradeInfoSchema(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"asset_data": "str",
"min_amount": "str",
"max_amount": "str",
"precision": "float",
}
attribute_map = {
"asset_data": "assetData",
"min_amount": "minAmount",
"max_amount": "maxAmount",
"precision": "precision",
}
def __init__(
self, asset_data=None, min_amount=None, max_amount=None, precision=None
): # noqa: E501
"""RelayerApiAssetDataTradeInfoSchema - a model defined in OpenAPI""" # noqa: E501
self._asset_data = None
self._min_amount = None
self._max_amount = None
self._precision = None
self.discriminator = None
self.asset_data = asset_data
if min_amount is not None:
self.min_amount = min_amount
if max_amount is not None:
self.max_amount = max_amount
if precision is not None:
self.precision = precision
@property
def asset_data(self):
"""Gets the asset_data of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:return: The asset_data of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:rtype: str
"""
return self._asset_data
@asset_data.setter
def asset_data(self, asset_data):
"""Sets the asset_data of this RelayerApiAssetDataTradeInfoSchema.
:param asset_data: The asset_data of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:type: str
"""
if asset_data is None:
raise ValueError(
"Invalid value for `asset_data`, must not be `None`"
) # noqa: E501
if asset_data is not None and not re.search(
r"^0x(([0-9a-f][0-9a-f])+)?$", asset_data
): # noqa: E501
raise ValueError(
r"Invalid value for `asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`"
) # noqa: E501
self._asset_data = asset_data
@property
def min_amount(self):
"""Gets the min_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:return: The min_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:rtype: str
"""
return self._min_amount
@min_amount.setter
def min_amount(self, min_amount):
"""Sets the min_amount of this RelayerApiAssetDataTradeInfoSchema.
:param min_amount: The min_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:type: str
"""
if min_amount is not None and not re.search(
r"^\\d+$", min_amount
): # noqa: E501
raise ValueError(
r"Invalid value for `min_amount`, must be a follow pattern or equal to `/^\\d+$/`"
) # noqa: E501
self._min_amount = min_amount
@property
def max_amount(self):
"""Gets the max_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:return: The max_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:rtype: str
"""
return self._max_amount
@max_amount.setter
def max_amount(self, max_amount):
"""Sets the max_amount of this RelayerApiAssetDataTradeInfoSchema.
:param max_amount: The max_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:type: str
"""
if max_amount is not None and not re.search(
r"^\\d+$", max_amount
): # noqa: E501
raise ValueError(
r"Invalid value for `max_amount`, must be a follow pattern or equal to `/^\\d+$/`"
) # noqa: E501
self._max_amount = max_amount
@property
def precision(self):
"""Gets the precision of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:return: The precision of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:rtype: float
"""
return self._precision
@precision.setter
def precision(self, precision):
"""Sets the precision of this RelayerApiAssetDataTradeInfoSchema.
:param precision: The precision of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501
:type: float
"""
self._precision = precision
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RelayerApiAssetDataTradeInfoSchema):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_asset_data_trade_info_schema.py | relayer_api_asset_data_trade_info_schema.py |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class RelayerApiErrorResponseSchemaValidationErrors(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {"field": "str", "code": "int", "reason": "str"}
attribute_map = {"field": "field", "code": "code", "reason": "reason"}
def __init__(self, field=None, code=None, reason=None): # noqa: E501
"""RelayerApiErrorResponseSchemaValidationErrors - a model defined in OpenAPI""" # noqa: E501
self._field = None
self._code = None
self._reason = None
self.discriminator = None
self.field = field
self.code = code
self.reason = reason
@property
def field(self):
"""Gets the field of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:return: The field of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:rtype: str
"""
return self._field
@field.setter
def field(self, field):
"""Sets the field of this RelayerApiErrorResponseSchemaValidationErrors.
:param field: The field of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:type: str
"""
if field is None:
raise ValueError(
"Invalid value for `field`, must not be `None`"
) # noqa: E501
self._field = field
@property
def code(self):
"""Gets the code of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:return: The code of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:rtype: int
"""
return self._code
@code.setter
def code(self, code):
"""Sets the code of this RelayerApiErrorResponseSchemaValidationErrors.
:param code: The code of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:type: int
"""
if code is None:
raise ValueError(
"Invalid value for `code`, must not be `None`"
) # noqa: E501
if code is not None and code > 1006: # noqa: E501
raise ValueError(
"Invalid value for `code`, must be a value less than or equal to `1006`"
) # noqa: E501
if code is not None and code < 1000: # noqa: E501
raise ValueError(
"Invalid value for `code`, must be a value greater than or equal to `1000`"
) # noqa: E501
self._code = code
@property
def reason(self):
"""Gets the reason of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:return: The reason of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:rtype: str
"""
return self._reason
@reason.setter
def reason(self, reason):
"""Sets the reason of this RelayerApiErrorResponseSchemaValidationErrors.
:param reason: The reason of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501
:type: str
"""
if reason is None:
raise ValueError(
"Invalid value for `reason`, must not be `None`"
) # noqa: E501
self._reason = reason
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value,
)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(
other, RelayerApiErrorResponseSchemaValidationErrors
):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 0x-sra-client | /0x-sra-client-4.0.0.tar.gz/0x-sra-client-4.0.0/src/zero_ex/sra_client/models/relayer_api_error_response_schema_validation_errors.py | relayer_api_error_response_schema_validation_errors.py |