code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
import redis import uuid import json import textwrap import shlex import base64 import signal import socket import logging import time from . import typchk DefaultTimeout = 10 # seconds logger = logging.getLogger('g8core') class Timeout(Exception): pass class JobNotFound(Exception): pass class Return: def __init__(self, payload): self._payload = payload @property def payload(self): return self._payload @property def id(self): return self._payload['id'] @property def data(self): """ data returned by the process. Only available if process output data with the correct core level """ return self._payload['data'] @property def level(self): """data message level (if any)""" return self._payload['level'] @property def starttime(self): """timestamp""" return self._payload['starttime'] / 1000 @property def time(self): """execution time in millisecond""" return self._payload['time'] @property def state(self): """ exit state """ return self._payload['state'] @property def stdout(self): streams = self._payload.get('streams', None) return streams[0] if streams is not None and len(streams) >= 1 else '' @property def stderr(self): streams = self._payload.get('streams', None) return streams[1] if streams is not None and len(streams) >= 2 else '' def __repr__(self): return str(self) def __str__(self): tmpl = """\ STATE: {state} STDOUT: {stdout} STDERR: {stderr} DATA: {data} """ return textwrap.dedent(tmpl).format(state=self.state, stdout=self.stdout, stderr=self.stderr, data=self.data) class Response: def __init__(self, client, id): self._client = client self._id = id self._queue = 'result:{}'.format(id) @property def id(self): return self._id @property def exists(self): r = self._client._redis flag = '{}:flag'.format(self._queue) return r.rpoplpush(flag, flag) is not None def get(self, timeout=None): if timeout is None: timeout = self._client.timeout r = self._client._redis start = time.time() maxwait = timeout while maxwait > 0: if not self.exists: raise JobNotFound(self.id) v = r.brpoplpush(self._queue, self._queue, 10) if v is not None: payload = json.loads(v.decode()) r = Return(payload) logger.debug('%s << %s, stdout="%s", stderr="%s", data="%s"', self._id, r.state, r.stdout, r.stderr, r.data[:1000]) return r logger.debug('%s still waiting (%ss)', self._id, int(time.time() - start)) maxwait -= 10 raise Timeout() class InfoManager: def __init__(self, client): self._client = client def cpu(self): return self._client.json('info.cpu', {}) def nic(self): return self._client.json('info.nic', {}) def mem(self): return self._client.json('info.mem', {}) def disk(self): return self._client.json('info.disk', {}) def os(self): return self._client.json('info.os', {}) def port(self): return self._client.json('info.port', {}) def version(self): return self._client.json('info.version', {}) class JobManager: _job_chk = typchk.Checker({ 'id': str, }) _kill_chk = typchk.Checker({ 'id': str, 'signal': int, }) def __init__(self, client): self._client = client def list(self, id=None): """ List all running jobs :param id: optional ID for the job to list """ args = {'id': id} self._job_chk.check(args) return self._client.json('job.list', args) def kill(self, id, signal=signal.SIGTERM): """ Kill a job with given id :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable :param id: job id to kill """ args = { 'id': id, 'signal': int(signal), } self._kill_chk.check(args) return self._client.json('job.kill', args) class ProcessManager: _process_chk = typchk.Checker({ 'pid': int, }) _kill_chk = typchk.Checker({ 'pid': int, 'signal': int, }) def __init__(self, client): self._client = client def list(self, id=None): """ List all running processes :param id: optional PID for the process to list """ args = {'pid': id} self._process_chk.check(args) return self._client.json('process.list', args) def kill(self, pid, signal=signal.SIGTERM): """ Kill a process with given pid :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable :param pid: PID to kill """ args = { 'pid': pid, 'signal': int(signal), } self._kill_chk.check(args) return self._client.json('process.kill', args) class FilesystemManager: def __init__(self, client): self._client = client def open(self, file, mode='r', perm=0o0644): """ Opens a file on the node :param file: file path to open :param mode: open mode :param perm: file permission in octet form mode: 'r' read only 'w' write only (truncate) '+' read/write 'x' create if not exist 'a' append :return: a file descriptor """ args = { 'file': file, 'mode': mode, 'perm': perm, } return self._client.json('filesystem.open', args) def exists(self, path): """ Check if path exists :param path: path to file/dir :return: boolean """ args = { 'path': path, } return self._client.json('filesystem.exists', args) def list(self, path): """ List all entries in directory :param path: path to dir :return: list of director entries """ args = { 'path': path, } return self._client.json('filesystem.list', args) def mkdir(self, path): """ Make a new directory == mkdir -p path :param path: path to directory to create :return: """ args = { 'path': path, } return self._client.json('filesystem.mkdir', args) def remove(self, path): """ Removes a path (recursively) :param path: path to remove :return: """ args = { 'path': path, } return self._client.json('filesystem.remove', args) def move(self, path, destination): """ Move a path to destination :param path: source :param destination: destination :return: """ args = { 'path': path, 'destination': destination, } return self._client.json('filesystem.move', args) def chmod(self, path, mode, recursive=False): """ Change file/dir permission :param path: path of file/dir to change :param mode: octet mode :param recursive: apply chmod recursively :return: """ args = { 'path': path, 'mode': mode, 'recursive': recursive, } return self._client.json('filesystem.chmod', args) def chown(self, path, user, group, recursive=False): """ Change file/dir owner :param path: path of file/dir :param user: user name :param group: group name :param recursive: apply chown recursively :return: """ args = { 'path': path, 'user': user, 'group': group, 'recursive': recursive, } return self._client.json('filesystem.chown', args) def read(self, fd): """ Read a block from the given file descriptor :param fd: file descriptor :return: bytes """ args = { 'fd': fd, } data = self._client.json('filesystem.read', args) return base64.decodebytes(data.encode()) def write(self, fd, bytes): """ Write a block of bytes to an open file descriptor (that is open with one of the writing modes :param fd: file descriptor :param bytes: bytes block to write :return: :note: don't overkill the node with large byte chunks, also for large file upload check the upload method. """ args = { 'fd': fd, 'block': base64.encodebytes(bytes).decode(), } return self._client.json('filesystem.write', args) def close(self, fd): """ Close file :param fd: file descriptor :return: """ args = { 'fd': fd, } return self._client.json('filesystem.close', args) def upload(self, remote, reader): """ Uploads a file :param remote: remote file name :param reader: an object that implements the read(size) method (typically a file descriptor) :return: """ fd = self.open(remote, 'w') while True: chunk = reader.read(512 * 1024) if chunk == b'': break self.write(fd, chunk) self.close(fd) def download(self, remote, writer): """ Downloads a file :param remote: remote file name :param writer: an object the implements the write(bytes) interface (typical a file descriptor) :return: """ fd = self.open(remote) while True: chunk = self.read(fd) if chunk == b'': break writer.write(chunk) self.close(fd) def upload_file(self, remote, local): """ Uploads a file :param remote: remote file name :param local: local file name :return: """ file = open(local, 'rb') self.upload(remote, file) def download_file(self, remote, local): """ Downloads a file :param remote: remote file name :param local: local file name :return: """ file = open(local, 'wb') self.download(remote, file) class BaseClient: _system_chk = typchk.Checker({ 'name': str, 'args': [str], 'dir': str, 'stdin': str, 'env': typchk.Or(typchk.Map(str, str), typchk.IsNone()), }) _bash_chk = typchk.Checker({ 'stdin': str, 'script': str, }) def __init__(self, timeout=None): if timeout is None: self.timeout = DefaultTimeout else: self.timeout = timeout self._info = InfoManager(self) self._job = JobManager(self) self._process = ProcessManager(self) self._filesystem = FilesystemManager(self) self._ip = IPManager(self) @property def info(self): return self._info @property def job(self): return self._job @property def process(self): return self._process @property def filesystem(self): return self._filesystem @property def ip(self): return self._ip def raw(self, command, arguments, queue=None, max_time=None): """ Implements the low level command call, this needs to build the command structure and push it on the correct queue. :param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...) check documentation for list of built in commands :param arguments: A dict of required command arguments depends on the command name. :return: Response object """ raise NotImplemented() def sync(self, command, arguments): """ Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result :return: Result object """ response = self.raw(command, arguments) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('invalid response: %s' % result.state, result) return result def json(self, command, arguments): """ Same as self.sync except it assumes the returned result is json, and loads the payload of the return object :Return: Data """ result = self.sync(command, arguments) if result.level != 20: raise RuntimeError('invalid result level, expecting json(20) got (%d)' % result.level) return json.loads(result.data) def ping(self): """ Ping a node, checking for it's availability. a Ping should never fail unless the node is not reachable or not responsive. :return: """ response = self.raw('core.ping', {}) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('invalid response: %s' % result.state) return json.loads(result.data) def system(self, command, dir='', stdin='', env=None): """ Execute a command :param command: command to execute (with its arguments) ex: `ls -l /root` :param dir: CWD of command :param stdin: Stdin data to feed to the command stdin :param env: dict with ENV variables that will be exported to the command :return: """ parts = shlex.split(command) if len(parts) == 0: raise ValueError('invalid command') args = { 'name': parts[0], 'args': parts[1:], 'dir': dir, 'stdin': stdin, 'env': env, } self._system_chk.check(args) response = self.raw(command='core.system', arguments=args) return response def bash(self, script, stdin=''): """ Execute a bash script, or run a process inside a bash shell. :param script: Script to execute (can be multiline script) :param stdin: Stdin data to feed to the script :return: """ args = { 'script': script, 'stdin': stdin, } self._bash_chk.check(args) response = self.raw(command='bash', arguments=args) return response class ContainerClient(BaseClient): class ContainerZerotierManager: def __init__(self, client, container): self._container = container self._client = client def info(self): return self._client.json('corex.zerotier.info', {'container': self._container}) def list(self): return self._client.json('corex.zerotier.list', {'container': self._container}) _raw_chk = typchk.Checker({ 'container': int, 'command': { 'command': str, 'arguments': typchk.Any(), 'queue': typchk.Or(str, typchk.IsNone()), 'max_time': typchk.Or(int, typchk.IsNone()), } }) def __init__(self, client, container): super().__init__(client.timeout) self._client = client self._container = container self._zerotier = ContainerClient.ContainerZerotierManager(client, container) # not (self) we use core0 client @property def container(self): return self._container @property def zerotier(self): return self._zerotier def raw(self, command, arguments, queue=None, max_time=None): """ Implements the low level command call, this needs to build the command structure and push it on the correct queue. :param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...) check documentation for list of built in commands :param arguments: A dict of required command arguments depends on the command name. :return: Response object """ args = { 'container': self._container, 'command': { 'command': command, 'arguments': arguments, 'queue': queue, 'max_time': max_time, }, } # check input self._raw_chk.check(args) response = self._client.raw('corex.dispatch', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to dispatch command to container: %s' % result.data) cmd_id = json.loads(result.data) return self._client.response_for(cmd_id) class ContainerManager: _create_chk = typchk.Checker({ 'root': str, 'mount': typchk.Or( typchk.Map(str, str), typchk.IsNone() ), 'host_network': bool, 'nics': [{ 'type': typchk.Enum('default', 'bridge', 'zerotier', 'vlan', 'vxlan'), 'id': typchk.Or(str, typchk.Missing()), 'name': typchk.Or(str, typchk.Missing()), 'hwaddr': typchk.Or(str, typchk.Missing()), 'config': typchk.Or( typchk.Missing, { 'dhcp': typchk.Or(bool, typchk.Missing()), 'cidr': typchk.Or(str, typchk.Missing()), 'gateway': typchk.Or(str, typchk.Missing()), 'dns': typchk.Or([str], typchk.Missing()), } ) }], 'port': typchk.Or( typchk.Map(int, int), typchk.IsNone() ), 'privileged': bool, 'hostname': typchk.Or( str, typchk.IsNone() ), 'storage': typchk.Or(str, typchk.IsNone()), 'tags': typchk.Or([str], typchk.IsNone()) }) _terminate_chk = typchk.Checker({ 'container': int }) DefaultNetworking = object() def __init__(self, client): self._client = client def create(self, root_url, mount=None, host_network=False, nics=DefaultNetworking, port=None, hostname=None, privileged=True, storage=None, tags=None): """ Creater a new container with the given root flist, mount points and zerotier id, and connected to the given bridges :param root_url: The root filesystem flist :param mount: a dict with {host_source: container_target} mount points. where host_source directory must exists. host_source can be a url to a flist to mount. :param host_network: Specify if the container should share the same network stack as the host. if True, container creation ignores both zerotier, bridge and ports arguments below. Not giving errors if provided. :param nics: Configure the attached nics to the container each nic object is a dict of the format { 'type': nic_type # default, bridge, zerotier, vlan, or vxlan (note, vlan and vxlan only supported by ovs) 'id': id # depends on the type, bridge name, zerotier network id, the vlan tag or the vxlan id 'name': name of the nic inside the container (ignored in zerotier type) 'hwaddr': Mac address of nic. 'config': { # config is only honored for bridge, vlan, and vxlan types 'dhcp': bool, 'cidr': static_ip # ip/mask 'gateway': gateway 'dns': [dns] } } :param port: A dict of host_port: container_port pairs (only if default networking is enabled) Example: `port={8080: 80, 7000:7000}` :param hostname: Specific hostname you want to give to the container. if None it will automatically be set to core-x, x beeing the ID of the container :param privileged: If true, container runs in privileged mode. :param storage: A Url to the ardb storage to use to mount the root flist (or any other mount that requires g8fs) if not provided, the default one from core0 configuration will be used. """ if nics == self.DefaultNetworking: nics = [{'type': 'default'}] elif nics is None: nics = [] args = { 'root': root_url, 'mount': mount, 'host_network': host_network, 'nics': nics, 'port': port, 'hostname': hostname, 'privileged': privileged, 'storage': storage, 'tags': tags, } # validate input self._create_chk.check(args) response = self._client.raw('corex.create', args) return response def list(self): """ List running containers :return: a dict with {container_id: <container info object>} """ return self._client.json('corex.list', {}) def find(self, *tags): """ Find containers that matches set of tags :param tags: :return: """ tags = list(map(str, tags)) return self._client.json('corex.find', {'tags': tags}) def terminate(self, container): """ Terminate a container given it's id :param container: container id :return: """ args = { 'container': container, } self._terminate_chk.check(args) response = self._client.raw('corex.terminate', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to terminate container: %s' % result.data) def client(self, container): """ Return a client instance that is bound to that container. :param container: container id :return: Client object bound to the specified container id """ return ContainerClient(self._client, container) class IPManager: class IPBridgeManager: def __init__(self, client): self._client = client def add(self, name, hwaddr=None): args = { 'name': name, 'hwaddr': hwaddr, } return self._client.json("ip.bridge.add", args) def delete(self, name): args = { 'name': name, } return self._client.json("ip.bridge.del", args) def addif(self, name, inf): args = { 'name': name, 'inf': inf, } return self._client.json('ip.bridge.addif', args) def delif(self, name, inf): args = { 'name': name, 'inf': inf, } return self._client.json('ip.bridge.delif', args) class IPLinkManager: def __init__(self, client): self._client = client def up(self, link): args = { 'name': link, } return self._client.json('ip.link.up', args) def down(self, link): args = { 'name': link, } return self._client.json('ip.link.down', args) def name(self, link, name): args = { 'name': link, 'new': name, } return self._client.json('ip.link.name', args) def list(self): return self._client.json('ip.link.list', {}) class IPAddrManager: def __init__(self, client): self._client = client def add(self, link, ip): args = { 'name': link, 'ip': ip, } return self._client.json('ip.addr.add', args) def delete(self, link, ip): args = { 'name': link, 'ip': ip, } return self._client.json('ip.addr.del', args) def list(self, link): args = { 'name': link, } return self._client.json('ip.addr.list', args) class IPRouteManager: def __init__(self, client): self._client = client def add(self, dev, dst, gw=None): args = { 'dev': dev, 'dst': dst, 'gw': gw, } return self._client.json('ip.route.add', args) def delete(self, dev, dst, gw=None): args = { 'dev': dev, 'dst': dst, 'gw': gw, } return self._client.json('ip.route.del', args) def list(self): return self._client.json('ip.route.list', {}) def __init__(self, client): self._client = client self._bridge = IPManager.IPBridgeManager(client) self._link = IPManager.IPLinkManager(client) self._addr = IPManager.IPAddrManager(client) self._route = IPManager.IPRouteManager(client) @property def bridge(self): return self._bridge @property def link(self): return self._link @property def addr(self): return self._addr @property def route(self): return self._route class BridgeManager: _bridge_create_chk = typchk.Checker({ 'name': str, 'hwaddr': str, 'network': { 'mode': typchk.Or(typchk.Enum('static', 'dnsmasq'), typchk.IsNone()), 'nat': bool, 'settings': typchk.Map(str, str), } }) _bridge_delete_chk = typchk.Checker({ 'name': str, }) def __init__(self, client): self._client = client def create(self, name, hwaddr=None, network=None, nat=False, settings={}): """ Create a bridge with the given name, hwaddr and networking setup :param name: name of the bridge (must be unique), 15 characters or less, and not equal to "default". :param hwaddr: MAC address of the bridge. If none, a one will be created for u :param network: Networking mode, options are none, static, and dnsmasq :param nat: If true, SNAT will be enabled on this bridge. (IF and ONLY IF an IP is set on the bridge via the settings, otherwise flag will be ignored) (the cidr attribute of either static, or dnsmasq modes) :param settings: Networking setting, depending on the selected mode. none: no settings, bridge won't get any ip settings static: settings={'cidr': 'ip/net'} bridge will get assigned the given IP address dnsmasq: settings={'cidr': 'ip/net', 'start': 'ip', 'end': 'ip'} bridge will get assigned the ip in cidr and each running container that is attached to this IP will get IP from the start/end range. Netmask of the range is the netmask part of the provided cidr. if nat is true, SNAT rules will be automatically added in the firewall. """ args = { 'name': name, 'hwaddr': hwaddr, 'network': { 'mode': network, 'nat': nat, 'settings': settings, } } self._bridge_create_chk.check(args) response = self._client.raw('bridge.create', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to create bridge %s' % result.data) return json.loads(result.data) def list(self): """ List all available bridges :return: list of bridge names """ response = self._client.raw('bridge.list', {}) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to list bridges: %s' % result.data) return json.loads(result.data) def delete(self, bridge): """ Delete a bridge by name :param bridge: bridge name :return: """ args = { 'name': bridge, } self._bridge_delete_chk.check(args) response = self._client.raw('bridge.delete', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to list delete: %s' % result.data) class DiskManager: _mktable_chk = typchk.Checker({ 'disk': str, 'table_type': typchk.Enum('aix', 'amiga', 'bsd', 'dvh', 'gpt', 'mac', 'msdos', 'pc98', 'sun', 'loop') }) _mkpart_chk = typchk.Checker({ 'disk': str, 'start': typchk.Or(int, str), 'end': typchk.Or(int, str), 'part_type': typchk.Enum('primary', 'logical', 'extended'), }) _getpart_chk = typchk.Checker({ 'disk': str, 'part': str, }) _rmpart_chk = typchk.Checker({ 'disk': str, 'number': int, }) _mount_chk = typchk.Checker({ 'options': str, 'source': str, 'target': str, }) _umount_chk = typchk.Checker({ 'source': str, }) def __init__(self, client): self._client = client def list(self): """ List available block devices """ response = self._client.raw('disk.list', {}) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to list disks: %s' % result.stderr) if result.level != 20: # 20 is JSON output. raise RuntimeError('invalid response type from disk.list command') data = result.data.strip() if data: return json.loads(data) else: return {} def mktable(self, disk, table_type='gpt'): """ Make partition table on block device. :param disk: device name (sda, sdb, etc...) :param table_type: Partition table type as accepted by parted """ args = { 'disk': disk, 'table_type': table_type, } self._mktable_chk.check(args) response = self._client.raw('disk.mktable', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to create table: %s' % result.stderr) def getinfo(self, disk, part=''): """ Get more info about a disk or a disk partition :param disk: (sda, sdb, etc..) :param part: (sda1, sdb2, etc...) :return: a dict with {"blocksize", "start", "size", and "free" sections} """ args = { "disk": disk, "part": part, } self._getpart_chk.check(args) response = self._client.raw('disk.getinfo', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to get info: %s' % result.data) if result.level != 20: # 20 is JSON output. raise RuntimeError('invalid response type from disk.getinfo command') data = result.data.strip() if data: return json.loads(data) else: return {} def mkpart(self, disk, start, end, part_type='primary'): """ Make partition on disk :param disk: device name (sda, sdb, etc...) :param start: partition start as accepted by parted mkpart :param end: partition end as accepted by parted mkpart :param part_type: partition type as accepted by parted mkpart """ args = { 'disk': disk, 'start': start, 'end': end, 'part_type': part_type, } self._mkpart_chk.check(args) response = self._client.raw('disk.mkpart', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to create partition: %s' % result.stderr) def rmpart(self, disk, number): """ Remove partion from disk :param disk: device name (sda, sdb, etc...) :param number: Partition number (starting from 1) """ args = { 'disk': disk, 'number': number, } self._rmpart_chk.check(args) response = self._client.raw('disk.rmpart', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to remove partition: %s' % result.stderr) def mount(self, source, target, options=[]): """ Mount partion on target :param source: Full partition path like /dev/sda1 :param target: Mount point :param options: Optional mount options """ if len(options) == 0: options = [''] args = { 'options': ','.join(options), 'source': source, 'target': target, } self._mount_chk.check(args) response = self._client.raw('disk.mount', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to mount partition: %s' % result.stderr) def umount(self, source): """ Unmount partion :param source: Full partition path like /dev/sda1 """ args = { 'source': source, } self._umount_chk.check(args) response = self._client.raw('disk.umount', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to umount partition: %s' % result.stderr) class BtrfsManager: _create_chk = typchk.Checker({ 'label': str, 'metadata': typchk.Enum("raid0", "raid1", "raid5", "raid6", "raid10", "dup", "single", ""), 'data': typchk.Enum("raid0", "raid1", "raid5", "raid6", "raid10", "dup", "single", ""), 'devices': [str], 'overwrite': bool, }) _device_chk = typchk.Checker({ 'mountpoint': str, 'devices': (str,), }) _subvol_chk = typchk.Checker({ 'path': str, }) _subvol_quota_chk = typchk.Checker({ 'path': str, 'limit': str, }) _subvol_snapshot_chk = typchk.Checker({ 'source': str, 'destination': str, 'read_only': bool, }) def __init__(self, client): self._client = client def list(self): """ List all btrfs filesystem """ return self._client.json('btrfs.list', {}) def info(self, mountpoint): """ Get btrfs fs info """ return self._client.json('btrfs.info', {'mountpoint': mountpoint}) def create(self, label, devices, metadata_profile="", data_profile="", overwrite=False): """ Create a btrfs filesystem with the given label, devices, and profiles :param label: name/label :param devices : array of devices (/dev/sda1, etc...) :metadata_profile: raid0, raid1, raid5, raid6, raid10, dup or single :data_profile: same as metadata profile :overwrite: force creation of the filesystem. Overwrite any existing filesystem """ args = { 'label': label, 'metadata': metadata_profile, 'data': data_profile, 'devices': devices, 'overwrite': overwrite } self._create_chk.check(args) self._client.sync('btrfs.create', args) def device_add(self, mountpoint, *device): """ Add one or more devices to btrfs filesystem mounted under `mountpoint` :param mountpoint: mount point of the btrfs system :param devices: one ore more devices to add :return: """ if len(device) == 0: return args = { 'mountpoint': mountpoint, 'devices': device, } self._device_chk.check(args) self._client.sync('btrfs.device_add', args) def device_remove(self, mountpoint, *device): """ Remove one or more devices from btrfs filesystem mounted under `mountpoint` :param mountpoint: mount point of the btrfs system :param devices: one ore more devices to remove :return: """ if len(device) == 0: return args = { 'mountpoint': mountpoint, 'devices': device, } self._device_chk.check(args) self._client.sync('btrfs.device_remove', args) def subvol_create(self, path): """ Create a btrfs subvolume in the specified path :param path: path to create """ args = { 'path': path } self._subvol_chk.check(args) self._client.sync('btrfs.subvol_create', args) def subvol_list(self, path): """ List a btrfs subvolume in the specified path :param path: path to be listed """ return self._client.json('btrfs.subvol_list', { 'path': path }) def subvol_delete(self, path): """ Delete a btrfs subvolume in the specified path :param path: path to delete """ args = { 'path': path } self._subvol_chk.check(args) self._client.sync('btrfs.subvol_delete', args) def subvol_quota(self, path, limit): """ Apply a quota to a btrfs subvolume in the specified path :param path: path to apply the quota for (it has to be the path of the subvol) :param limit: the limit to Apply """ args = { 'path': path, 'limit': limit, } self._subvol_quota_chk.check(args) self._client.sync('btrfs.subvol_quota', args) def subvol_snapshot(self, source, destination, read_only=False): """ Take a snapshot :param source: source path of subvol :param destination: destination path of snapshot :param read_only: Set read-only on the snapshot :return: """ args = { "source": source, "destination": destination, "read_only": read_only, } self._subvol_snapshot_chk.check(args) self._client.sync('btrfs.subvol_snapshot', args) class ZerotierManager: _network_chk = typchk.Checker({ 'network': str, }) def __init__(self, client): self._client = client def join(self, network): """ Join a zerotier network :param network: network id to join :return: """ args = {'network': network} self._network_chk.check(args) response = self._client.raw('zerotier.join', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to join zerotier network: %s', result.stderr) def leave(self, network): """ Leave a zerotier network :param network: network id to leave :return: """ args = {'network': network} self._network_chk.check(args) response = self._client.raw('zerotier.leave', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to leave zerotier network: %s', result.stderr) def list(self): """ List joined zerotier networks :return: list of joined networks with their info """ return self._client.json('zerotier.list', {}) def info(self): """ Display zerotier status info :return: dict of zerotier statusinfo """ return self._client.json('zerotier.info', {}) class KvmManager: _iotune_dict = { 'totalbytessecset': bool, 'totalbytessec': int, 'readbytessecset': bool, 'readbytessec': int, 'writebytessecset': bool, 'writebytessec': int, 'totaliopssecset': bool, 'totaliopssec': int, 'readiopssecset': bool, 'readiopssec': int, 'writeiopssecset': bool, 'writeiopssec': int, 'totalbytessecmaxset': bool, 'totalbytessecmax': int, 'readbytessecmaxset': bool, 'readbytessecmax': int, 'writebytessecmaxset': bool, 'writebytessecmax': int, 'totaliopssecmaxset': bool, 'totaliopssecmax': int, 'readiopssecmaxset': bool, 'readiopssecmax': int, 'writeiopssecmaxset': bool, 'writeiopssecmax': int, 'totalbytessecmaxlengthset': bool, 'totalbytessecmaxlength': int, 'readbytessecmaxlengthset': bool, 'readbytessecmaxlength': int, 'writebytessecmaxlengthset': bool, 'writebytessecmaxlength': int, 'totaliopssecmaxlengthset': bool, 'totaliopssecmaxlength': int, 'readiopssecmaxlengthset': bool, 'readiopssecmaxlength': int, 'writeiopssecmaxlengthset': bool, 'writeiopssecmaxlength': int, 'sizeiopssecset': bool, 'sizeiopssec': int, 'groupnameset': bool, 'groupname': str, } _media_dict = { 'type': typchk.Or( typchk.Enum('disk', 'cdrom'), typchk.Missing() ), 'url': str, 'iotune': typchk.Or( _iotune_dict, typchk.Missing() ) } _create_chk = typchk.Checker({ 'name': str, 'media': typchk.Length([_media_dict], 1), 'cpu': int, 'memory': int, 'nics': [{ 'type': typchk.Enum('default', 'bridge', 'vxlan', 'vlan'), 'id': typchk.Or(str, typchk.Missing()), 'hwaddr': typchk.Or(str, typchk.Missing()), }], 'port': typchk.Or( typchk.Map(int, int), typchk.IsNone() ), }) _domain_action_chk = typchk.Checker({ 'uuid': str, }) _man_disk_action_chk = typchk.Checker({ 'uuid': str, 'media': _media_dict, }) _man_nic_action_chk = typchk.Checker({ 'uuid': str, 'type': typchk.Enum('default', 'bridge', 'vxlan', 'vlan'), 'id': typchk.Or(str, typchk.Missing()), 'hwaddr': typchk.Or(str, typchk.Missing()), }) _migrate_action_chk = typchk.Checker({ 'uuid': str, 'desturi': str, }) _limit_disk_io_dict = { 'uuid': str, 'media': _media_dict, } _limit_disk_io_dict.update(_iotune_dict) _limit_disk_io_action_chk = typchk.Checker(_limit_disk_io_dict) def __init__(self, client): self._client = client def create(self, name, media, cpu=2, memory=512, nics=None, port=None): """ :param name: Name of the kvm domain :param media: array of media objects to attach to the machine, where the first object is the boot device each media object is a dict of {url, type} where type can be one of 'disk', or 'cdrom', or empty (default to disk) example: [{'url': 'nbd+unix:///test?socket=/tmp/ndb.socket'}, {'type': 'cdrom': '/somefile.iso'} :param cpu: number of vcpu cores :param memory: memory in MiB :param port: A dict of host_port: container_port pairs Example: `port={8080: 80, 7000:7000}` Only supported if default network is used :param nics: Configure the attached nics to the container each nic object is a dict of the format { 'type': nic_type # default, bridge, vlan, or vxlan (note, vlan and vxlan only supported by ovs) 'id': id # depends on the type, bridge name (bridge type) zerotier network id (zertier type), the vlan tag or the vxlan id } :return: uuid of the virtual machine """ if nics is None: nics = [] args = { 'name': name, 'media': media, 'cpu': cpu, 'memory': memory, 'nics': nics, 'port': port, } self._create_chk.check(args) return self._client.sync('kvm.create', args) def destroy(self, uuid): """ Destroy a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.destroy', args) def shutdown(self, uuid): """ Shutdown a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.shutdown', args) def reboot(self, uuid): """ Reboot a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.reboot', args) def reset(self, uuid): """ Reset (Force reboot) a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.reset', args) def pause(self, uuid): """ Pause a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.pause', args) def resume(self, uuid): """ Resume a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.resume', args) def info(self, uuid): """ Get info about a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) return self._client.json('kvm.info', args) def infops(self, uuid): """ Get info per second about a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) return self._client.json('kvm.infops', args) def attach_disk(self, uuid, media): """ Attach a disk to a machine :param uuid: uuid of the kvm container (same as the used in create) :param media: the media object to attach to the machine media object is a dict of {url, and type} where type can be one of 'disk', or 'cdrom', or empty (default to disk) examples: {'url': 'nbd+unix:///test?socket=/tmp/ndb.socket'}, {'type': 'cdrom': '/somefile.iso'} :return: """ args = { 'uuid': uuid, 'media': media, } self._man_disk_action_chk.check(args) self._client.sync('kvm.attach_disk', args) def detach_disk(self, uuid, media): """ Detach a disk from a machine :param uuid: uuid of the kvm container (same as the used in create) :param media: the media object to attach to the machine media object is a dict of {url, and type} where type can be one of 'disk', or 'cdrom', or empty (default to disk) examples: {'url': 'nbd+unix:///test?socket=/tmp/ndb.socket'}, {'type': 'cdrom': '/somefile.iso'} :return: """ args = { 'uuid': uuid, 'media': media, } self._man_disk_action_chk.check(args) self._client.sync('kvm.detach_disk', args) def add_nic(self, uuid, type, id=None, hwaddr=None): """ Add a nic to a machine :param uuid: uuid of the kvm container (same as the used in create) :param type: nic_type # default, bridge, vlan, or vxlan (note, vlan and vxlan only supported by ovs) param id: id # depends on the type, bridge name (bridge type) zerotier network id (zertier type), the vlan tag or the vxlan id param hwaddr: the hardware address of the nic :return: """ args = { 'uuid': uuid, 'type': type, 'id': id, 'hwaddr': hwaddr, } self._man_nic_action_chk.check(args) return self._client.json('kvm.add_nic', args) def remove_nic(self, uuid, type, id=None, hwaddr=None): """ Remove a nic from a machine :param uuid: uuid of the kvm container (same as the used in create) :param type: nic_type # default, bridge, vlan, or vxlan (note, vlan and vxlan only supported by ovs) param id: id # depends on the type, bridge name (bridge type) zerotier network id (zertier type), the vlan tag or the vxlan id param hwaddr: the hardware address of the nic :return: """ args = { 'uuid': uuid, 'type': type, 'id': id, 'hwaddr': hwaddr, } self._man_nic_action_chk.check(args) return self._client.json('kvm.remove_nic', args) def limit_disk_io(self, uuid, media, totalbytessecset=False, totalbytessec=0, readbytessecset=False, readbytessec=0, writebytessecset=False, writebytessec=0, totaliopssecset=False, totaliopssec=0, readiopssecset=False, readiopssec=0, writeiopssecset=False, writeiopssec=0, totalbytessecmaxset=False, totalbytessecmax=0, readbytessecmaxset=False, readbytessecmax=0, writebytessecmaxset=False, writebytessecmax=0, totaliopssecmaxset=False, totaliopssecmax=0, readiopssecmaxset=False, readiopssecmax=0, writeiopssecmaxset=False, writeiopssecmax=0, totalbytessecmaxlengthset=False, totalbytessecmaxlength=0, readbytessecmaxlengthset=False, readbytessecmaxlength=0, writebytessecmaxlengthset=False, writebytessecmaxlength=0, totaliopssecmaxlengthset=False, totaliopssecmaxlength=0, readiopssecmaxlengthset=False, readiopssecmaxlength=0, writeiopssecmaxlengthset=False, writeiopssecmaxlength=0, sizeiopssecset=False, sizeiopssec=0, groupnameset=False, groupname=''): """ Remove a nic from a machine :param uuid: uuid of the kvm container (same as the used in create) :param media: the media to limit the diskio :return: """ args = { 'uuid': uuid, 'media': media, 'totalbytessecset': totalbytessecset, 'totalbytessec': totalbytessec, 'readbytessecset': readbytessecset, 'readbytessec': readbytessec, 'writebytessecset': writebytessecset, 'writebytessec': writebytessec, 'totaliopssecset': totaliopssecset, 'totaliopssec': totaliopssec, 'readiopssecset': readiopssecset, 'readiopssec': readiopssec, 'writeiopssecset': writeiopssecset, 'writeiopssec': writeiopssec, 'totalbytessecmaxset': totalbytessecmaxset, 'totalbytessecmax': totalbytessecmax, 'readbytessecmaxset': readbytessecmaxset, 'readbytessecmax': readbytessecmax, 'writebytessecmaxset': writebytessecmaxset, 'writebytessecmax': writebytessecmax, 'totaliopssecmaxset': totaliopssecmaxset, 'totaliopssecmax': totaliopssecmax, 'readiopssecmaxset': readiopssecmaxset, 'readiopssecmax': readiopssecmax, 'writeiopssecmaxset': writeiopssecmaxset, 'writeiopssecmax': writeiopssecmax, 'totalbytessecmaxlengthset': totalbytessecmaxlengthset, 'totalbytessecmaxlength': totalbytessecmaxlength, 'readbytessecmaxlengthset': readbytessecmaxlengthset, 'readbytessecmaxlength': readbytessecmaxlength, 'writebytessecmaxlengthset': writebytessecmaxlengthset, 'writebytessecmaxlength': writebytessecmaxlength, 'totaliopssecmaxlengthset': totaliopssecmaxlengthset, 'totaliopssecmaxlength': totaliopssecmaxlength, 'readiopssecmaxlengthset': readiopssecmaxlengthset, 'readiopssecmaxlength': readiopssecmaxlength, 'writeiopssecmaxlengthset': writeiopssecmaxlengthset, 'writeiopssecmaxlength': writeiopssecmaxlength, 'sizeiopssecset': sizeiopssecset, 'sizeiopssec': sizeiopssec, 'groupnameset': groupnameset, 'groupname': groupname, } self._limit_disk_io_action_chk.check(args) self._client.sync('kvm.limit_disk_io', args) def migrate(self, uuid, desturi): """ Migrate a vm to another node :param uuid: uuid of the kvm container (same as the used in create) :param desturi: the uri of the destination node :return: """ args = { 'uuid': uuid, 'desturi': desturi, } self._migrate_action_chk.check(args) self._client.sync('kvm.migrate', args) def list(self): """ List configured domains :return: """ return self._client.json('kvm.list', {}) class Logger: _level_chk = typchk.Checker({ 'level': typchk.Enum("CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG"), }) def __init__(self, client): self._client = client def set_level(self, level): """ Set the log level of the g8os :param level: the level to be set can be one of ("CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG") """ args = { 'level': level, } self._level_chk.check(args) return self._client.json('logger.set_level', args) def reopen(self): """ Reopen log file """ return self._client.json('logger.reopen', {}) class Nft: _port_chk = typchk.Checker({ 'port': int, 'interface': typchk.Or(str, typchk.Missing()), 'subnet': typchk.Or(str, typchk.Missing()), }) def __init__(self, client): self._client = client def open_port(self, port, interface=None, subnet=None): """ open port :param port: then port number :param interface: an optional interface to open the port for :param subnet: an optional subnet to open the port for """ args = { 'port': port, 'interface': interface, 'subnet': subnet, } self._port_chk.check(args) return self._client.json('nft.open_port', args) def drop_port(self, port, interface=None, subnet=None): """ close an opened port (takes the same parameters passed in open) :param port: then port number :param interface: an optional interface to close the port for :param subnet: an optional subnet to close the port for """ args = { 'port': port, 'interface': interface, 'subnet': subnet, } self._port_chk.check(args) return self._client.json('nft.drop_port', args) class Config: def __init__(self, client): self._client = client def get(self): """ Get the config of g8os """ return self._client.json('config.get', {}) class Experimental: def __init__(self, client): pass class Client(BaseClient): def __init__(self, host, port=6379, password="", db=0, ssl=True, timeout=None, testConnectionAttempts=3): super().__init__(timeout=timeout) socket_timeout = (timeout + 5) if timeout else 15 self._redis = redis.Redis(host=host, port=port, password=password, db=db, ssl=ssl, socket_timeout=socket_timeout, socket_keepalive=True, socket_keepalive_options={ socket.TCP_KEEPINTVL: 1, socket.TCP_KEEPCNT: 10 }) self._container_manager = ContainerManager(self) self._bridge_manager = BridgeManager(self) self._disk_manager = DiskManager(self) self._btrfs_manager = BtrfsManager(self) self._zerotier = ZerotierManager(self) self._experimntal = Experimental(self) self._kvm = KvmManager(self) self._logger = Logger(self) self._nft = Nft(self) self._config = Config(self) if testConnectionAttempts: for _ in range(testConnectionAttempts): try: self.ping() except: pass else: return raise RuntimeError("Could not connect to remote host %s" % host) @property def experimental(self): return self._experimntal @property def container(self): return self._container_manager @property def bridge(self): return self._bridge_manager @property def disk(self): return self._disk_manager @property def btrfs(self): return self._btrfs_manager @property def zerotier(self): return self._zerotier @property def kvm(self): return self._kvm @property def logger(self): return self._logger @property def nft(self): return self._nft @property def config(self): return self._config def raw(self, command, arguments, queue=None, max_time=None): """ Implements the low level command call, this needs to build the command structure and push it on the correct queue. :param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...) check documentation for list of built in commands :param arguments: A dict of required command arguments depends on the command name. :return: Response object """ id = str(uuid.uuid4()) payload = { 'id': id, 'command': command, 'arguments': arguments, 'queue': queue, 'max_time': max_time, } flag = 'result:{}:flag'.format(id) self._redis.rpush('core:default', json.dumps(payload)) if self._redis.brpoplpush(flag, flag, DefaultTimeout) is None: Timeout('failed to queue job {}'.format(id)) logger.debug('%s >> g8core.%s(%s)', id, command, ', '.join(("%s=%s" % (k, v) for k, v in arguments.items()))) return Response(self, id) def response_for(self, id): return Response(self, id)
0-core-client
/0-core-client-1.1.0a4.tar.gz/0-core-client-1.1.0a4/zeroos/core0/client/client.py
client.py
missing = object() def primitive(typ): return typ in [str, int, float, bool] class CheckerException(BaseException): pass class Tracker(BaseException): def __init__(self, base): self._base = base self._reason = None self._branches = [] @property def branches(self): return self._branches def copy(self): l = self._base.copy() t = Tracker(l) t._reason = self._reason return t def push(self, s): t = self.copy() t._base.append(str(s)) return t def pop(self): t = self.copy() t._base.pop() return t def reason(self, reason): self._reason = reason return self def branch(self, tracker): t = tracker.copy() self._branches.append(t) def __str__(self): u = "/".join(self._base) if self._reason is not None: u = '[{}] at -> {}'.format(self._reason, u) for branch in self.branches: u += '\n -> {}'.format(branch) return u def __repr__(self): return str(self) class Option: def __init__(self): raise NotImplementedError() def check(self, object, t): raise NotImplementedError() class Or(Option): def __init__(self, *types): self._checkers = [] for typ in types: self._checkers.append(Checker(typ)) def check(self, object, t): bt = t.copy() for chk in self._checkers: try: chk.check(object, bt) return except Tracker as tx: t.branch(tx) raise t.reason('all branches failed') class IsNone(Option): def __init__(self): pass def check(self, object, t): if object is not None: raise t.reason('is not none') class Missing(Option): def __init__(self): pass def check(self, object, t): if object != missing: raise t.reason('is not missing') class Any(Option): def __init__(self): pass def check(self, object, t): return class Length(Option): def __init__(self, typ, min=None, max=None): self._checker = Checker(typ) if min is None and max is None: raise ValueError("you have to pass wither min or max to the length type checker") self._min = min self._max = max def check(self, object, t): self._checker.check(object, t) if self._min is not None and len(object) < self._min: raise t.reason('invalid length, expecting more than or equal {} got {}'.format(self._min, len(object))) if self._max is not None and len(object) > self._max: raise t.reason('invalid length, expecting less than or equal {} got {}'.format(self._max, len(object))) class Map(Option): def __init__(self, key_type, value_type): self._key = Checker(key_type) self._value = Checker(value_type) def check(self, object, t): if not isinstance(object, dict): raise t.reason('expecting a dict, got {}'.format(type(object))) for k, v in object.items(): tx = t.push(k) self._key.check(k, tx) tv = t.push('{}[value]'.format(k)) self._value.check(v, tv) class Enum(Option): def __init__(self, *valid): self._valid = valid def check(self, object, t): if not isinstance(object, str): raise t.reason('expecting string, got {}'.format(type(object))) if object not in self._valid: raise t.reason('value "{}" not in enum'.format(object)) class Checker: """ Build a type checker to check method inputs A Checker takes a type definition as following c = Checker(<type-def>) then use c to check inputs as valid = c.check(value) type-def: - primitive types (str, bool, int, float) - composite types ([str], [int], etc...) - dicts types ({'name': str, 'age': float, etc...}) To build a more complex type-def u can use the available Options in typechk module - Or(type-def, type-def, ...) - Missing() (Only make sense in dict types) - IsNone() (accept None value) Example of type definition A dict object, with the following attributes - `name` of type string - optional `age` which can be int, or float - A list of children each has - string name - float age c = Checker({ 'name': str, 'age': Or(int, float, Missing()), 'children': [{'name': str, 'age': float}] }) c.check({'name': 'azmy', 'age': 34, children:[]}) # passes c.check({'name': 'azmy', children:[]}) # passes c.check({'age': 34, children:[]}) # does not pass c.check({'name': 'azmy', children:[{'name': 'yahia', 'age': 4.0}]}) # passes c.check({'name': 'azmy', children:[{'name': 'yahia', 'age': 4.0}, {'name': 'yassine'}]}) # does not pass """ def __init__(self, tyepdef): self._typ = tyepdef def check(self, object, tracker=None): if tracker is None: tracker = Tracker([]).push('/') return self._check(self._typ, object, tracker) def _check_list(self, typ, obj_list, t): for i, elem in enumerate(obj_list): tx = t.push('[{}]'.format(i)) self._check(typ, elem, tx) def _check_dict(self, typ, obj_dict, t): given = [] for name, value in obj_dict.items(): tx = t.push(name) if name not in typ: raise tx.reason('unknown key "{}"'.format(name)) given.append(name) attr_type = typ[name] self._check(attr_type, value, tx) if len(given) == len(typ): return type_keys = list(typ.keys()) for key in given: type_keys.remove(key) for required in type_keys: tx = t.push(required) self._check(typ[required], missing, tx) def _check(self, typ, object, t): if isinstance(typ, Option): return typ.check(object, t) atyp = type(object) if primitive(atyp) and atyp != typ: raise t.reason('invalid type, expecting {}'.format(typ)) if isinstance(typ, list): if atyp != list: raise t.reason('expecting a list') self._check_list(typ[0], object, t) if isinstance(typ, tuple): if atyp != tuple: raise t.reason('expecting a tuple') self._check_list(typ[0], object, t) elif isinstance(typ, dict): if atyp != dict: raise t.reason('expecting a dict') self._check_dict(typ, object, t)
0-core-client
/0-core-client-1.1.0a4.tar.gz/0-core-client-1.1.0a4/zeroos/core0/client/typchk.py
typchk.py
import json import collections from datetime import datetime from uuid import UUID from enum import Enum from dateutil import parser # python2/3 compatible basestring, for use in to_dict try: basestring except NameError: basestring = str def timestamp_from_datetime(datetime): """ Convert from datetime format to timestamp format Input: Time in datetime format Output: Time in timestamp format """ return datetime.strftime('%Y-%m-%dT%H:%M:%S.%fZ') def timestamp_to_datetime(timestamp): """ Convert from timestamp format to datetime format Input: Time in timestamp format Output: Time in datetime format """ return parser.parse(timestamp).replace(tzinfo=None) def has_properties(cls, property, child_properties): for child_prop in child_properties: if getattr(property, child_prop, None) is None: return False return True def list_factory(val, member_type): if not isinstance(val, list): raise ValueError('list_factory: value must be a list') return [val_factory(v, member_type) for v in val] def dict_factory(val, objmap): # objmap is a dict outlining the structure of this value # its format is {'attrname': {'datatype': [type], 'required': bool}} objdict = {} for attrname, attrdict in objmap.items(): value = val.get(attrname) if value is not None: for dt in attrdict['datatype']: try: if isinstance(dt, dict): objdict[attrname] = dict_factory(value, attrdict) else: objdict[attrname] = val_factory(value, [dt]) except Exception: pass if objdict.get(attrname) is None: raise ValueError('dict_factory: {attr}: unable to instantiate with any supplied type'.format(attr=attrname)) elif attrdict.get('required'): raise ValueError('dict_factory: {attr} is required'.format(attr=attrname)) return objdict def val_factory(val, datatypes): """ return an instance of `val` that is of type `datatype`. keep track of exceptions so we can produce meaningful error messages. """ exceptions = [] for dt in datatypes: try: if isinstance(val, dt): return val return type_handler_object(val, dt) except Exception as e: exceptions.append(str(e)) # if we get here, we never found a valid value. raise an error raise ValueError('val_factory: Unable to instantiate {val} from types {types}. Exceptions: {excs}'. format(val=val, types=datatypes, excs=exceptions)) def to_json(cls, indent=0): """ serialize to JSON :rtype: str """ # for consistency, use as_dict then go to json from there return json.dumps(cls.as_dict(), indent=indent) def to_dict(cls, convert_datetime=True): """ return a dict representation of the Event and its sub-objects `convert_datetime` controls whether datetime objects are converted to strings or not :rtype: dict """ def todict(obj): """ recurse the objects and represent as a dict use the registered handlers if possible """ data = {} if isinstance(obj, dict): for (key, val) in obj.items(): data[key] = todict(val) return data if not convert_datetime and isinstance(obj, datetime): return obj elif type_handler_value(obj): return type_handler_value(obj) elif isinstance(obj, collections.Sequence) and not isinstance(obj, basestring): return [todict(v) for v in obj] elif hasattr(obj, "__dict__"): for key, value in obj.__dict__.items(): if not callable(value) and not key.startswith('_'): data[key] = todict(value) return data else: return obj return todict(cls) class DatetimeHandler(object): """ output datetime objects as iso-8601 compliant strings """ @classmethod def flatten(cls, obj): """flatten""" return timestamp_from_datetime(obj) @classmethod def restore(cls, data): """restore""" return timestamp_to_datetime(data) class UUIDHandler(object): """ output UUID objects as a string """ @classmethod def flatten(cls, obj): """flatten""" return str(obj) @classmethod def restore(cls, data): """restore""" return UUID(data) class EnumHandler(object): """ output Enum objects as their value """ @classmethod def flatten(cls, obj): """flatten""" return obj.value @classmethod def restore(cls, data): """ cannot restore here because we don't know what type of enum it is """ raise NotImplementedError handlers = { datetime: DatetimeHandler, Enum: EnumHandler, UUID: UUIDHandler, } def handler_for(obj): """return the handler for the object type""" for handler_type in handlers: if isinstance(obj, handler_type): return handlers[handler_type] try: for handler_type in handlers: if issubclass(obj, handler_type): return handlers[handler_type] except TypeError: # if obj isn't a class, issubclass will raise a TypeError pass def type_handler_value(obj): """ return the serialized (flattened) value from the registered handler for the type """ handler = handler_for(obj) if handler: return handler().flatten(obj) def type_handler_object(val, objtype): """ return the deserialized (restored) value from the registered handler for the type """ handler = handlers.get(objtype) if handler: return handler().restore(val) else: return objtype(val)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/client_support.py
client_support.py
import requests from .graphs_service import GraphsService from .health_service import HealthService from .nodes_service import NodesService from .storageclusters_service import StorageclustersService from .vdisks_service import VdisksService class Client: def __init__(self, base_uri=""): self.base_url = base_uri self.session = requests.Session() self.graphs = GraphsService(self) self.health = HealthService(self) self.nodes = NodesService(self) self.storageclusters = StorageclustersService(self) self.vdisks = VdisksService(self) def is_goraml_class(self, data): # check if a data is go-raml generated class # we currently only check the existence # of as_json method op = getattr(data, "as_json", None) if callable(op): return True return False def set_auth_header(self, val): ''' set authorization header value''' self.session.headers.update({"Authorization": val}) def _get_headers(self, headers, content_type): if content_type: contentheader = {"Content-Type": content_type} if headers is None: headers = contentheader else: headers.update(contentheader) return headers def _handle_data(self, uri, data, headers, params, content_type, method): headers = self._get_headers(headers, content_type) if self.is_goraml_class(data): data = data.as_json() if content_type == "multipart/form-data": # when content type is multipart/formdata remove the content-type header # as requests will set this itself with correct boundary headers.pop('Content-Type') res = method(uri, files=data, headers=headers, params=params) elif data is None: res = method(uri, headers=headers, params=params) elif type(data) is str: res = method(uri, data=data, headers=headers, params=params) else: res = method(uri, json=data, headers=headers, params=params) res.raise_for_status() return res def post(self, uri, data, headers, params, content_type): return self._handle_data(uri, data, headers, params, content_type, self.session.post) def put(self, uri, data, headers, params, content_type): return self._handle_data(uri, data, headers, params, content_type, self.session.put) def patch(self, uri, data, headers, params, content_type): return self._handle_data(uri, data, headers, params, content_type, self.session.patch) def get(self, uri, data, headers, params, content_type): return self._handle_data(uri, data, headers, params, content_type, self.session.get) def delete(self, uri, data, headers, params, content_type): return self._handle_data(uri, data, headers, params, content_type, self.session.delete)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/client.py
client.py
class NodesService: def __init__(self, client): self.client = client def DeleteBridge(self, bridgeid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Remove bridge It is method for DELETE /nodes/{nodeid}/bridges/{bridgeid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/bridges/"+bridgeid return self.client.delete(uri, None, headers, query_params, content_type) def GetBridge(self, bridgeid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get bridge details It is method for GET /nodes/{nodeid}/bridges/{bridgeid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/bridges/"+bridgeid return self.client.get(uri, None, headers, query_params, content_type) def ListBridges(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ List bridges It is method for GET /nodes/{nodeid}/bridges """ uri = self.client.base_url + "/nodes/"+nodeid+"/bridges" return self.client.get(uri, None, headers, query_params, content_type) def CreateBridge(self, data, nodeid, headers=None, query_params=None, content_type="application/json"): """ Creates a new bridge It is method for POST /nodes/{nodeid}/bridges """ uri = self.client.base_url + "/nodes/"+nodeid+"/bridges" return self.client.post(uri, data, headers, query_params, content_type) def GetContainerCPUInfo(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of all CPUs in the container It is method for GET /nodes/{nodeid}/containers/{containername}/cpus """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/cpus" return self.client.get(uri, None, headers, query_params, content_type) def GetContainerDiskInfo(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of all the disks in the container It is method for GET /nodes/{nodeid}/containers/{containername}/disks """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/disks" return self.client.get(uri, None, headers, query_params, content_type) def FileDelete(self, data, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete file from container It is method for DELETE /nodes/{nodeid}/containers/{containername}/filesystem """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/filesystem" return self.client.delete(uri, data, headers, query_params, content_type) def FileDownload(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Download file from container It is method for GET /nodes/{nodeid}/containers/{containername}/filesystem """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/filesystem" return self.client.get(uri, None, headers, query_params, content_type) def FileUpload(self, data, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Upload file to container It is method for POST /nodes/{nodeid}/containers/{containername}/filesystem """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/filesystem" return self.client.post(uri, data, headers, query_params, content_type) def GetContainerOSInfo(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of the container OS It is method for GET /nodes/{nodeid}/containers/{containername}/info """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/info" return self.client.get(uri, None, headers, query_params, content_type) def KillContainerJob(self, jobid, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Kills the job It is method for DELETE /nodes/{nodeid}/containers/{containername}/jobs/{jobid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/jobs/"+jobid return self.client.delete(uri, None, headers, query_params, content_type) def GetContainerJob(self, jobid, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get details of a submitted job on the container It is method for GET /nodes/{nodeid}/containers/{containername}/jobs/{jobid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/jobs/"+jobid return self.client.get(uri, None, headers, query_params, content_type) def SendSignalToJob(self, data, jobid, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Send signal to the job It is method for POST /nodes/{nodeid}/containers/{containername}/jobs/{jobid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/jobs/"+jobid return self.client.post(uri, data, headers, query_params, content_type) def KillAllContainerJobs(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Kill all running jobs on the container It is method for DELETE /nodes/{nodeid}/containers/{containername}/jobs """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/jobs" return self.client.delete(uri, None, headers, query_params, content_type) def ListContainerJobs(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ List running jobs on the container It is method for GET /nodes/{nodeid}/containers/{containername}/jobs """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/jobs" return self.client.get(uri, None, headers, query_params, content_type) def StartContainerJob(self, data, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Start a new job in this container It is method for POST /nodes/{nodeid}/containers/{containername}/jobs """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/jobs" return self.client.post(uri, data, headers, query_params, content_type) def GetContainerMemInfo(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information about the memory in the container It is method for GET /nodes/{nodeid}/containers/{containername}/mem """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/mem" return self.client.get(uri, None, headers, query_params, content_type) def GetContainerNicInfo(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information about the network interfaces in the container It is method for GET /nodes/{nodeid}/containers/{containername}/nics """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/nics" return self.client.get(uri, None, headers, query_params, content_type) def PingContainer(self, data, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Ping this container It is method for POST /nodes/{nodeid}/containers/{containername}/ping """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/ping" return self.client.post(uri, data, headers, query_params, content_type) def KillContainerProcess(self, processid, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Kills the process by sending sigterm signal to the process. If it is still running, a sigkill signal will be sent to the process It is method for DELETE /nodes/{nodeid}/containers/{containername}/processes/{processid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/processes/"+processid return self.client.delete(uri, None, headers, query_params, content_type) def GetContainerProcess(self, processid, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get process details It is method for GET /nodes/{nodeid}/containers/{containername}/processes/{processid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/processes/"+processid return self.client.get(uri, None, headers, query_params, content_type) def SendSignalToProcess(self, data, processid, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Send signal to the process It is method for POST /nodes/{nodeid}/containers/{containername}/processes/{processid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/processes/"+processid return self.client.post(uri, data, headers, query_params, content_type) def ListContainerProcesses(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get running processes in this container It is method for GET /nodes/{nodeid}/containers/{containername}/processes """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/processes" return self.client.get(uri, None, headers, query_params, content_type) def StartContainer(self, data, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Start container instance It is method for POST /nodes/{nodeid}/containers/{containername}/start """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/start" return self.client.post(uri, data, headers, query_params, content_type) def GetContainerState(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get aggregated consumption of container + all processes (CPU, memory, etc.) It is method for GET /nodes/{nodeid}/containers/{containername}/state """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/state" return self.client.get(uri, None, headers, query_params, content_type) def StopContainer(self, data, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Stop container instance It is method for POST /nodes/{nodeid}/containers/{containername}/stop """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername+"/stop" return self.client.post(uri, data, headers, query_params, content_type) def DeleteContainer(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete container instance It is method for DELETE /nodes/{nodeid}/containers/{containername} """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername return self.client.delete(uri, None, headers, query_params, content_type) def GetContainer(self, containername, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get container It is method for GET /nodes/{nodeid}/containers/{containername} """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers/"+containername return self.client.get(uri, None, headers, query_params, content_type) def ListContainers(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ List running containers It is method for GET /nodes/{nodeid}/containers """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers" return self.client.get(uri, None, headers, query_params, content_type) def CreateContainer(self, data, nodeid, headers=None, query_params=None, content_type="application/json"): """ Create a new container It is method for POST /nodes/{nodeid}/containers """ uri = self.client.base_url + "/nodes/"+nodeid+"/containers" return self.client.post(uri, data, headers, query_params, content_type) def GetCPUInfo(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of all CPUs in the node It is method for GET /nodes/{nodeid}/cpus """ uri = self.client.base_url + "/nodes/"+nodeid+"/cpus" return self.client.get(uri, None, headers, query_params, content_type) def GetDiskInfo(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of all the disks in the node It is method for GET /nodes/{nodeid}/disks """ uri = self.client.base_url + "/nodes/"+nodeid+"/disks" return self.client.get(uri, None, headers, query_params, content_type) def GetGWFWConfig(self, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get current FW config It is method for GET /nodes/{nodeid}/gws/{gwname}/advanced/firewall """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/advanced/firewall" return self.client.get(uri, None, headers, query_params, content_type) def SetGWFWConfig(self, data, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Set FW config Once used you can not use gw.portforwards any longer It is method for POST /nodes/{nodeid}/gws/{gwname}/advanced/firewall """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/advanced/firewall" return self.client.post(uri, data, headers, query_params, content_type) def GetGWHTTPConfig(self, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get current HTTP config It is method for GET /nodes/{nodeid}/gws/{gwname}/advanced/http """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/advanced/http" return self.client.get(uri, None, headers, query_params, content_type) def SetGWHTTPConfig(self, data, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Set HTTP config Once used you can not use gw.httpproxxies any longer It is method for POST /nodes/{nodeid}/gws/{gwname}/advanced/http """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/advanced/http" return self.client.post(uri, data, headers, query_params, content_type) def DeleteDHCPHost(self, macaddress, interface, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete dhcp host It is method for DELETE /nodes/{nodeid}/gws/{gwname}/dhcp/{interface}/hosts/{macaddress} """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/dhcp/"+interface+"/hosts/"+macaddress return self.client.delete(uri, None, headers, query_params, content_type) def ListGWDHCPHosts(self, interface, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ List DHCPHosts for specified interface It is method for GET /nodes/{nodeid}/gws/{gwname}/dhcp/{interface}/hosts """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/dhcp/"+interface+"/hosts" return self.client.get(uri, None, headers, query_params, content_type) def AddGWDHCPHost(self, data, interface, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Add a dhcp host to a specified interface It is method for POST /nodes/{nodeid}/gws/{gwname}/dhcp/{interface}/hosts """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/dhcp/"+interface+"/hosts" return self.client.post(uri, data, headers, query_params, content_type) def DeleteGWForward(self, forwardid, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete portforward, forwardid = srcip:srcport It is method for DELETE /nodes/{nodeid}/gws/{gwname}/firewall/forwards/{forwardid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/firewall/forwards/"+forwardid return self.client.delete(uri, None, headers, query_params, content_type) def GetGWForwards(self, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get list for IPv4 Forwards It is method for GET /nodes/{nodeid}/gws/{gwname}/firewall/forwards """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/firewall/forwards" return self.client.get(uri, None, headers, query_params, content_type) def CreateGWForwards(self, data, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Create a new Portforwarding It is method for POST /nodes/{nodeid}/gws/{gwname}/firewall/forwards """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/firewall/forwards" return self.client.post(uri, data, headers, query_params, content_type) def DeleteHTTPProxies(self, proxyid, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete HTTP proxy It is method for DELETE /nodes/{nodeid}/gws/{gwname}/httpproxies/{proxyid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/httpproxies/"+proxyid return self.client.delete(uri, None, headers, query_params, content_type) def GetHTTPProxy(self, proxyid, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get info of HTTP proxy It is method for GET /nodes/{nodeid}/gws/{gwname}/httpproxies/{proxyid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/httpproxies/"+proxyid return self.client.get(uri, None, headers, query_params, content_type) def ListHTTPProxies(self, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ List for HTTP proxies It is method for GET /nodes/{nodeid}/gws/{gwname}/httpproxies """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/httpproxies" return self.client.get(uri, None, headers, query_params, content_type) def CreateHTTPProxies(self, data, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Create new HTTP proxies It is method for POST /nodes/{nodeid}/gws/{gwname}/httpproxies """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/httpproxies" return self.client.post(uri, data, headers, query_params, content_type) def StartGateway(self, data, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Start Gateway instance It is method for POST /nodes/{nodeid}/gws/{gwname}/start """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/start" return self.client.post(uri, data, headers, query_params, content_type) def StopGateway(self, data, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Stop gateway instance It is method for POST /nodes/{nodeid}/gws/{gwname}/stop """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname+"/stop" return self.client.post(uri, data, headers, query_params, content_type) def DeleteGateway(self, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete gateway instance It is method for DELETE /nodes/{nodeid}/gws/{gwname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname return self.client.delete(uri, None, headers, query_params, content_type) def GetGateway(self, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get gateway It is method for GET /nodes/{nodeid}/gws/{gwname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname return self.client.get(uri, None, headers, query_params, content_type) def UpdateGateway(self, data, gwname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Update Gateway It is method for PUT /nodes/{nodeid}/gws/{gwname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws/"+gwname return self.client.put(uri, data, headers, query_params, content_type) def ListGateways(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ List running gateways It is method for GET /nodes/{nodeid}/gws """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws" return self.client.get(uri, None, headers, query_params, content_type) def CreateGW(self, data, nodeid, headers=None, query_params=None, content_type="application/json"): """ Create a new gateway It is method for POST /nodes/{nodeid}/gws """ uri = self.client.base_url + "/nodes/"+nodeid+"/gws" return self.client.post(uri, data, headers, query_params, content_type) def GetNodeOSInfo(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of the OS of the node It is method for GET /nodes/{nodeid}/info """ uri = self.client.base_url + "/nodes/"+nodeid+"/info" return self.client.get(uri, None, headers, query_params, content_type) def KillNodeJob(self, jobid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Kills the job It is method for DELETE /nodes/{nodeid}/jobs/{jobid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/jobs/"+jobid return self.client.delete(uri, None, headers, query_params, content_type) def GetNodeJob(self, jobid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get the details of a submitted job It is method for GET /nodes/{nodeid}/jobs/{jobid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/jobs/"+jobid return self.client.get(uri, None, headers, query_params, content_type) def KillAllNodeJobs(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Kill all running jobs It is method for DELETE /nodes/{nodeid}/jobs """ uri = self.client.base_url + "/nodes/"+nodeid+"/jobs" return self.client.delete(uri, None, headers, query_params, content_type) def ListNodeJobs(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ List running jobs It is method for GET /nodes/{nodeid}/jobs """ uri = self.client.base_url + "/nodes/"+nodeid+"/jobs" return self.client.get(uri, None, headers, query_params, content_type) def GetMemInfo(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information about the memory in the node It is method for GET /nodes/{nodeid}/mem """ uri = self.client.base_url + "/nodes/"+nodeid+"/mem" return self.client.get(uri, None, headers, query_params, content_type) def GetNodeMounts(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of all the mountpoints on the node It is method for GET /nodes/{nodeid}/mounts """ uri = self.client.base_url + "/nodes/"+nodeid+"/mounts" return self.client.get(uri, None, headers, query_params, content_type) def GetNicInfo(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information about the network interfaces in the node It is method for GET /nodes/{nodeid}/nics """ uri = self.client.base_url + "/nodes/"+nodeid+"/nics" return self.client.get(uri, None, headers, query_params, content_type) def PingNode(self, data, nodeid, headers=None, query_params=None, content_type="application/json"): """ Ping this node It is method for POST /nodes/{nodeid}/ping """ uri = self.client.base_url + "/nodes/"+nodeid+"/ping" return self.client.post(uri, data, headers, query_params, content_type) def KillNodeProcess(self, processid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Kills the process by sending sigterm signal to the process. If it is still running, a sigkill signal will be sent to the process It is method for DELETE /nodes/{nodeid}/processes/{processid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/processes/"+processid return self.client.delete(uri, None, headers, query_params, content_type) def GetNodeProcess(self, processid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get process details It is method for GET /nodes/{nodeid}/processes/{processid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/processes/"+processid return self.client.get(uri, None, headers, query_params, content_type) def ListNodeProcesses(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get processes It is method for GET /nodes/{nodeid}/processes """ uri = self.client.base_url + "/nodes/"+nodeid+"/processes" return self.client.get(uri, None, headers, query_params, content_type) def RebootNode(self, data, nodeid, headers=None, query_params=None, content_type="application/json"): """ Immediately reboot the machine It is method for POST /nodes/{nodeid}/reboot """ uri = self.client.base_url + "/nodes/"+nodeid+"/reboot" return self.client.post(uri, data, headers, query_params, content_type) def GetNodeState(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ The aggregated consumption of node + all processes (cpu, memory, etc...) It is method for GET /nodes/{nodeid}/state """ uri = self.client.base_url + "/nodes/"+nodeid+"/state" return self.client.get(uri, None, headers, query_params, content_type) def GetStats(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get all statskeys of the node It is method for GET /nodes/{nodeid}/stats """ uri = self.client.base_url + "/nodes/"+nodeid+"/stats" return self.client.get(uri, None, headers, query_params, content_type) def DeleteStoragePoolDevice(self, deviceuuid, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Removes the device from the storage pool It is method for DELETE /nodes/{nodeid}/storagepools/{storagepoolname}/devices/{deviceuuid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/devices/"+deviceuuid return self.client.delete(uri, None, headers, query_params, content_type) def GetStoragePoolDeviceInfo(self, deviceuuid, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get information of the device It is method for GET /nodes/{nodeid}/storagepools/{storagepoolname}/devices/{deviceuuid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/devices/"+deviceuuid return self.client.get(uri, None, headers, query_params, content_type) def ListStoragePoolDevices(self, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ List the devices in the storage pool It is method for GET /nodes/{nodeid}/storagepools/{storagepoolname}/devices """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/devices" return self.client.get(uri, None, headers, query_params, content_type) def CreateStoragePoolDevices(self, data, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Add extra devices to this storage pool It is method for POST /nodes/{nodeid}/storagepools/{storagepoolname}/devices """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/devices" return self.client.post(uri, data, headers, query_params, content_type) def RollbackFilesystemSnapshot(self, data, snapshotname, filesystemname, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Rollback the file system to the state at the moment the snapshot was taken It is method for POST /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems/{filesystemname}/snapshots/{snapshotname}/rollback """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems/"+filesystemname+"/snapshots/"+snapshotname+"/rollback" return self.client.post(uri, data, headers, query_params, content_type) def DeleteFilesystemSnapshot(self, snapshotname, filesystemname, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete snapshot It is method for DELETE /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems/{filesystemname}/snapshots/{snapshotname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems/"+filesystemname+"/snapshots/"+snapshotname return self.client.delete(uri, None, headers, query_params, content_type) def GetFilesystemSnapshotInfo(self, snapshotname, filesystemname, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information on the snapshot It is method for GET /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems/{filesystemname}/snapshots/{snapshotname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems/"+filesystemname+"/snapshots/"+snapshotname return self.client.get(uri, None, headers, query_params, content_type) def ListFilesystemSnapshots(self, filesystemname, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ List snapshots of this file system It is method for GET /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems/{filesystemname}/snapshots """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems/"+filesystemname+"/snapshots" return self.client.get(uri, None, headers, query_params, content_type) def CreateSnapshot(self, data, filesystemname, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Create a new read-only snapshot of the current state of the vdisk It is method for POST /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems/{filesystemname}/snapshots """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems/"+filesystemname+"/snapshots" return self.client.post(uri, data, headers, query_params, content_type) def DeleteFilesystem(self, filesystemname, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete file system It is method for DELETE /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems/{filesystemname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems/"+filesystemname return self.client.delete(uri, None, headers, query_params, content_type) def GetFilesystemInfo(self, filesystemname, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed file system information It is method for GET /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems/{filesystemname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems/"+filesystemname return self.client.get(uri, None, headers, query_params, content_type) def ListFilesystems(self, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ List all file systems It is method for GET /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems" return self.client.get(uri, None, headers, query_params, content_type) def CreateFilesystem(self, data, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Create a new file system It is method for POST /nodes/{nodeid}/storagepools/{storagepoolname}/filesystems """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname+"/filesystems" return self.client.post(uri, data, headers, query_params, content_type) def DeleteStoragePool(self, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete the storage pool It is method for DELETE /nodes/{nodeid}/storagepools/{storagepoolname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname return self.client.delete(uri, None, headers, query_params, content_type) def GetStoragePoolInfo(self, storagepoolname, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of this storage pool It is method for GET /nodes/{nodeid}/storagepools/{storagepoolname} """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools/"+storagepoolname return self.client.get(uri, None, headers, query_params, content_type) def ListStoragePools(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ List storage pools present in the node It is method for GET /nodes/{nodeid}/storagepools """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools" return self.client.get(uri, None, headers, query_params, content_type) def CreateStoragePool(self, data, nodeid, headers=None, query_params=None, content_type="application/json"): """ Create a new storage pool in the node It is method for POST /nodes/{nodeid}/storagepools """ uri = self.client.base_url + "/nodes/"+nodeid+"/storagepools" return self.client.post(uri, data, headers, query_params, content_type) def GetVMInfo(self, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get statistical information about the virtual machine. It is method for GET /nodes/{nodeid}/vms/{vmid}/info """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid+"/info" return self.client.get(uri, None, headers, query_params, content_type) def MigrateVM(self, data, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Migrate the virtual machine to another host It is method for POST /nodes/{nodeid}/vms/{vmid}/migrate """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid+"/migrate" return self.client.post(uri, data, headers, query_params, content_type) def PauseVM(self, data, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Pauses the VM It is method for POST /nodes/{nodeid}/vms/{vmid}/pause """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid+"/pause" return self.client.post(uri, data, headers, query_params, content_type) def ResumeVM(self, data, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Resumes the virtual machine It is method for POST /nodes/{nodeid}/vms/{vmid}/resume """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid+"/resume" return self.client.post(uri, data, headers, query_params, content_type) def ShutdownVM(self, data, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Gracefully shutdown the virtual machine It is method for POST /nodes/{nodeid}/vms/{vmid}/shutdown """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid+"/shutdown" return self.client.post(uri, data, headers, query_params, content_type) def StartVM(self, data, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Start the virtual machine It is method for POST /nodes/{nodeid}/vms/{vmid}/start """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid+"/start" return self.client.post(uri, data, headers, query_params, content_type) def StopVM(self, data, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Stops the VM It is method for POST /nodes/{nodeid}/vms/{vmid}/stop """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid+"/stop" return self.client.post(uri, data, headers, query_params, content_type) def DeleteVM(self, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Deletes the virtual machine It is method for DELETE /nodes/{nodeid}/vms/{vmid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid return self.client.delete(uri, None, headers, query_params, content_type) def GetVM(self, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get the virtual machine object It is method for GET /nodes/{nodeid}/vms/{vmid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid return self.client.get(uri, None, headers, query_params, content_type) def UpdateVM(self, data, vmid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Updates the virtual machine It is method for PUT /nodes/{nodeid}/vms/{vmid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms/"+vmid return self.client.put(uri, data, headers, query_params, content_type) def ListVMs(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ List all virtual machines It is method for GET /nodes/{nodeid}/vms """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms" return self.client.get(uri, None, headers, query_params, content_type) def CreateVM(self, data, nodeid, headers=None, query_params=None, content_type="application/json"): """ Creates a new virtual machine It is method for POST /nodes/{nodeid}/vms """ uri = self.client.base_url + "/nodes/"+nodeid+"/vms" return self.client.post(uri, data, headers, query_params, content_type) def ExitZerotier(self, zerotierid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Exit the ZeroTier network It is method for DELETE /nodes/{nodeid}/zerotiers/{zerotierid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/zerotiers/"+zerotierid return self.client.delete(uri, None, headers, query_params, content_type) def GetZerotier(self, zerotierid, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get ZeroTier network details It is method for GET /nodes/{nodeid}/zerotiers/{zerotierid} """ uri = self.client.base_url + "/nodes/"+nodeid+"/zerotiers/"+zerotierid return self.client.get(uri, None, headers, query_params, content_type) def ListZerotier(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ List running ZeroTier networks It is method for GET /nodes/{nodeid}/zerotiers """ uri = self.client.base_url + "/nodes/"+nodeid+"/zerotiers" return self.client.get(uri, None, headers, query_params, content_type) def JoinZerotier(self, data, nodeid, headers=None, query_params=None, content_type="application/json"): """ Join ZeroTier network It is method for POST /nodes/{nodeid}/zerotiers """ uri = self.client.base_url + "/nodes/"+nodeid+"/zerotiers" return self.client.post(uri, data, headers, query_params, content_type) def DeleteNode(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Delete a node It is method for DELETE /nodes/{nodeid} """ uri = self.client.base_url + "/nodes/"+nodeid return self.client.delete(uri, None, headers, query_params, content_type) def GetNode(self, nodeid, headers=None, query_params=None, content_type="application/json"): """ Get detailed information of a node It is method for GET /nodes/{nodeid} """ uri = self.client.base_url + "/nodes/"+nodeid return self.client.get(uri, None, headers, query_params, content_type) def ListNodes(self, headers=None, query_params=None, content_type="application/json"): """ List all nodes It is method for GET /nodes """ uri = self.client.base_url + "/nodes" return self.client.get(uri, None, headers, query_params, content_type)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/nodes_service.py
nodes_service.py
class GraphsService: def __init__(self, client): self.client = client def DeleteDashboard(self, dashboardname, graphid, headers=None, query_params=None, content_type="application/json"): """ Delete a dashboard It is method for DELETE /graphs/{graphid}/dashboards/{dashboardname} """ uri = self.client.base_url + "/graphs/"+graphid+"/dashboards/"+dashboardname return self.client.delete(uri, None, headers, query_params, content_type) def GetDashboard(self, dashboardname, graphid, headers=None, query_params=None, content_type="application/json"): """ Get dashboard It is method for GET /graphs/{graphid}/dashboards/{dashboardname} """ uri = self.client.base_url + "/graphs/"+graphid+"/dashboards/"+dashboardname return self.client.get(uri, None, headers, query_params, content_type) def ListDashboards(self, graphid, headers=None, query_params=None, content_type="application/json"): """ List dashboards It is method for GET /graphs/{graphid}/dashboards """ uri = self.client.base_url + "/graphs/"+graphid+"/dashboards" return self.client.get(uri, None, headers, query_params, content_type) def CreateDashboard(self, data, graphid, headers=None, query_params=None, content_type="application/json"): """ Create Dashboard It is method for POST /graphs/{graphid}/dashboards """ uri = self.client.base_url + "/graphs/"+graphid+"/dashboards" return self.client.post(uri, data, headers, query_params, content_type) def GetGraph(self, graphid, headers=None, query_params=None, content_type="application/json"): """ Get a graph It is method for GET /graphs/{graphid} """ uri = self.client.base_url + "/graphs/"+graphid return self.client.get(uri, None, headers, query_params, content_type) def UpdateGraph(self, data, graphid, headers=None, query_params=None, content_type="application/json"): """ Update Graph It is method for PUT /graphs/{graphid} """ uri = self.client.base_url + "/graphs/"+graphid return self.client.put(uri, data, headers, query_params, content_type) def ListGraphs(self, headers=None, query_params=None, content_type="application/json"): """ List all graphs It is method for GET /graphs """ uri = self.client.base_url + "/graphs" return self.client.get(uri, None, headers, query_params, content_type)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/graphs_service.py
graphs_service.py
class VdisksService: def __init__(self, client): self.client = client def ResizeVdisk(self, data, vdiskid, headers=None, query_params=None, content_type="application/json"): """ Resize vdisk It is method for POST /vdisks/{vdiskid}/resize """ uri = self.client.base_url + "/vdisks/"+vdiskid+"/resize" return self.client.post(uri, data, headers, query_params, content_type) def RollbackVdisk(self, data, vdiskid, headers=None, query_params=None, content_type="application/json"): """ Rollback a vdisk to a previous state It is method for POST /vdisks/{vdiskid}/rollback """ uri = self.client.base_url + "/vdisks/"+vdiskid+"/rollback" return self.client.post(uri, data, headers, query_params, content_type) def DeleteVdisk(self, vdiskid, headers=None, query_params=None, content_type="application/json"): """ Delete Vdisk It is method for DELETE /vdisks/{vdiskid} """ uri = self.client.base_url + "/vdisks/"+vdiskid return self.client.delete(uri, None, headers, query_params, content_type) def GetVdiskInfo(self, vdiskid, headers=None, query_params=None, content_type="application/json"): """ Get vdisk information It is method for GET /vdisks/{vdiskid} """ uri = self.client.base_url + "/vdisks/"+vdiskid return self.client.get(uri, None, headers, query_params, content_type) def ListVdisks(self, headers=None, query_params=None, content_type="application/json"): """ List vdisks It is method for GET /vdisks """ uri = self.client.base_url + "/vdisks" return self.client.get(uri, None, headers, query_params, content_type) def CreateNewVdisk(self, data, headers=None, query_params=None, content_type="application/json"): """ Create a new vdisk, can be a copy from an existing vdisk It is method for POST /vdisks """ uri = self.client.base_url + "/vdisks" return self.client.post(uri, data, headers, query_params, content_type)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/vdisks_service.py
vdisks_service.py
import datetime import time def generate_rfc3339(d, local_tz=True): """ generate rfc3339 time format input : d = date type local_tz = use local time zone if true, otherwise mark as utc output : rfc3339 string date format. ex : `2008-04-02T20:00:00+07:00` """ try: if local_tz: d = datetime.datetime.fromtimestamp(d) else: d = datetime.datetime.utcfromtimestamp(d) except TypeError: pass if not isinstance(d, datetime.date): raise TypeError('Not timestamp or date object. Got %r.' % type(d)) if not isinstance(d, datetime.datetime): d = datetime.datetime(*d.timetuple()[:3]) return ('%04d-%02d-%02dT%02d:%02d:%02d%s' % (d.year, d.month, d.day, d.hour, d.minute, d.second, _generate_timezone(d, local_tz))) def _calculate_offset(date, local_tz): """ input : date : date type local_tz : if true, use system timezone, otherwise return 0 return the date of UTC offset. If date does not have any timezone info, we use local timezone, otherwise return 0 """ if local_tz: #handle year before 1970 most sytem there is no timezone information before 1970. if date.year < 1970: # Use 1972 because 1970 doesn't have a leap day t = time.mktime(date.replace(year=1972).timetuple) else: t = time.mktime(date.timetuple()) # handle daylightsaving, if daylightsaving use altzone, otherwise use timezone if time.localtime(t).tm_isdst: return -time.altzone else: return -time.timezone else: return 0 def _generate_timezone(date, local_tz): """ input : date : date type local_tz : bool offset generated from _calculate_offset offset in seconds offset = 0 -> +00:00 offset = 1800 -> +00:30 offset = -3600 -> -01:00 """ offset = _calculate_offset(date, local_tz) hour = abs(offset) // 3600 minute = abs(offset) % 3600 // 60 if offset < 0: return '%c%02d:%02d' % ("-", hour, minute) else: return '%c%02d:%02d' % ("+", hour, minute)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/client_utils.py
client_utils.py
import requests from .Bridge import Bridge from .BridgeCreate import BridgeCreate from .BridgeCreateSetting import BridgeCreateSetting from .CPUInfo import CPUInfo from .CPUStats import CPUStats from .CloudInit import CloudInit from .Cluster import Cluster from .ClusterCreate import ClusterCreate from .Container import Container from .ContainerListItem import ContainerListItem from .ContainerNIC import ContainerNIC from .ContainerNICconfig import ContainerNICconfig from .CoreStateResult import CoreStateResult from .CoreSystem import CoreSystem from .CreateContainer import CreateContainer from .CreateSnapshotReqBody import CreateSnapshotReqBody from .DHCP import DHCP from .Dashboard import Dashboard from .DashboardListItem import DashboardListItem from .DeleteFile import DeleteFile from .DiskInfo import DiskInfo from .DiskPartition import DiskPartition from .EnumBridgeCreateNetworkMode import EnumBridgeCreateNetworkMode from .EnumBridgeStatus import EnumBridgeStatus from .EnumClusterCreateClusterType import EnumClusterCreateClusterType from .EnumClusterCreateDriveType import EnumClusterCreateDriveType from .EnumClusterDriveType import EnumClusterDriveType from .EnumClusterStatus import EnumClusterStatus from .EnumContainerListItemStatus import EnumContainerListItemStatus from .EnumContainerNICStatus import EnumContainerNICStatus from .EnumContainerNICType import EnumContainerNICType from .EnumContainerStatus import EnumContainerStatus from .EnumDiskInfoType import EnumDiskInfoType from .EnumGWNICType import EnumGWNICType from .EnumGetGWStatus import EnumGetGWStatus from .EnumJobResultName import EnumJobResultName from .EnumJobResultState import EnumJobResultState from .EnumNicLinkType import EnumNicLinkType from .EnumNodeStatus import EnumNodeStatus from .EnumStoragePoolCreateDataProfile import EnumStoragePoolCreateDataProfile from .EnumStoragePoolCreateMetadataProfile import EnumStoragePoolCreateMetadataProfile from .EnumStoragePoolDataProfile import EnumStoragePoolDataProfile from .EnumStoragePoolDeviceStatus import EnumStoragePoolDeviceStatus from .EnumStoragePoolListItemStatus import EnumStoragePoolListItemStatus from .EnumStoragePoolMetadataProfile import EnumStoragePoolMetadataProfile from .EnumStoragePoolStatus import EnumStoragePoolStatus from .EnumStorageServerStatus import EnumStorageServerStatus from .EnumVMListItemStatus import EnumVMListItemStatus from .EnumVMStatus import EnumVMStatus from .EnumVdiskCreateType import EnumVdiskCreateType from .EnumVdiskListItemStatus import EnumVdiskListItemStatus from .EnumVdiskListItemType import EnumVdiskListItemType from .EnumVdiskStatus import EnumVdiskStatus from .EnumVdiskType import EnumVdiskType from .EnumZerotierListItemType import EnumZerotierListItemType from .EnumZerotierType import EnumZerotierType from .Filesystem import Filesystem from .FilesystemCreate import FilesystemCreate from .GW import GW from .GWCreate import GWCreate from .GWHost import GWHost from .GWNIC import GWNIC from .GWNICconfig import GWNICconfig from .GetGW import GetGW from .Graph import Graph from .HTTPProxy import HTTPProxy from .HTTPType import HTTPType from .HealthCheck import HealthCheck from .IPProtocol import IPProtocol from .Job import Job from .JobListItem import JobListItem from .JobResult import JobResult from .ListGW import ListGW from .MemInfo import MemInfo from .NicInfo import NicInfo from .NicLink import NicLink from .Node import Node from .NodeHealthCheck import NodeHealthCheck from .NodeMount import NodeMount from .OSInfo import OSInfo from .PortForward import PortForward from .Process import Process from .ProcessSignal import ProcessSignal from .Snapshot import Snapshot from .StoragePool import StoragePool from .StoragePoolCreate import StoragePoolCreate from .StoragePoolDevice import StoragePoolDevice from .StoragePoolListItem import StoragePoolListItem from .StorageServer import StorageServer from .VDiskLink import VDiskLink from .VM import VM from .VMCreate import VMCreate from .VMDiskInfo import VMDiskInfo from .VMInfo import VMInfo from .VMListItem import VMListItem from .VMMigrate import VMMigrate from .VMNicInfo import VMNicInfo from .VMUpdate import VMUpdate from .Vdisk import Vdisk from .VdiskCreate import VdiskCreate from .VdiskListItem import VdiskListItem from .VdiskResize import VdiskResize from .VdiskRollback import VdiskRollback from .WriteFile import WriteFile from .Zerotier import Zerotier from .ZerotierBridge import ZerotierBridge from .ZerotierJoin import ZerotierJoin from .ZerotierListItem import ZerotierListItem from .ZerotierRoute import ZerotierRoute from .client import Client as APIClient from .oauth2_client_itsyouonline import Oauth2ClientItsyouonline class Client: def __init__(self, base_uri=""): self.api = APIClient(base_uri) self.oauth2_client_itsyouonline = Oauth2ClientItsyouonline()
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/client/__init__.py
__init__.py
from enum import Enum from .Partition import Partition from .abstracts import Mountable class DiskType(Enum): ssd = "ssd" hdd = "hdd" nvme = "nvme" archive = "archive" cdrom = 'cdrom' class Disks: """Subobject to list disks""" def __init__(self, node): self.node = node self._client = node.client def list(self): """ List of disks on the node """ disks = [] disk_list = self._client.disk.list() if 'blockdevices' in disk_list: for disk_info in self._client.disk.list()['blockdevices']: disks.append(Disk( node=self.node, disk_info=disk_info )) return disks def get(self, name): """ return the disk called `name` @param name: name of the disk """ for disk in self.list(): if disk.name == name: return disk return None class Disk(Mountable): """Disk in a G8OS""" def __init__(self, node, disk_info): """ disk_info: dict returned by client.disk.list() """ # g8os client to talk to the node self.node = node self._client = node.client self.name = None self.size = None self.blocksize = None self.partition_table = None self.mountpoint = None self.model = None self._filesystems = [] self.type = None self.partitions = [] self._load(disk_info) @property def devicename(self): return "/dev/{}".format(self.name) @property def filesystems(self): self._populate_filesystems() return self._filesystems def _load(self, disk_info): self.name = disk_info['name'] detail = self._client.disk.getinfo(self.name) self.size = int(disk_info['size']) self.blocksize = detail['blocksize'] if detail['table'] != 'unknown': self.partition_table = detail['table'] self.mountpoint = disk_info['mountpoint'] self.model = disk_info['model'] self.type = self._disk_type(disk_info) for partition_info in disk_info.get('children', []) or []: self.partitions.append( Partition( disk=self, part_info=partition_info) ) def _populate_filesystems(self): """ look into all the btrfs filesystem and populate the filesystems attribute of the class with the detail of all the filesystem present on the disk """ self._filesystems = [] for fs in (self._client.btrfs.list() or []): for device in fs['devices']: if device['path'] == "/dev/{}".format(self.name): self._filesystems.append(fs) break def _disk_type(self, disk_info): """ return the type of the disk """ if disk_info['rota'] == "1": if disk_info['type'] == 'rom': return DiskType.cdrom # assume that if a disk is more than 7TB it's a SMR disk elif int(disk_info['size']) > (1024 * 1024 * 1024 * 1024 * 7): return DiskType.archive else: return DiskType.hdd else: if "nvme" in disk_info['name']: return DiskType.nvme else: return DiskType.ssd def mktable(self, table_type='gpt', overwrite=False): """ create a partition table on the disk @param table_type: Partition table type as accepted by parted @param overwrite: erase any existing partition table """ if self.partition_table is not None and overwrite is False: return self._client.disk.mktable( disk=self.name, table_type=table_type ) def mkpart(self, start, end, part_type="primary"): """ @param start: partition start as accepted by parted mkpart @param end: partition end as accepted by parted mkpart @param part_type: partition type as accepted by parted mkpart """ before = {p.name for p in self.partitions} self._client.disk.mkpart( self.name, start=start, end=end, part_type=part_type, ) after = {} for disk in self._client.disk.list()['blockdevices']: if disk['name'] != self.name: continue for part in disk.get('children', []): after[part['name']] = part name = set(after.keys()) - before part_info = after[list(name)[0]] partition = Partition( disk=self, part_info=part_info) self.partitions.append(partition) return partition def __str__(self): return "Disk <{}>".format(self.name) def __repr__(self): return str(self) def __eq__(self, other): return self.devicename == other.devicename
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/Disk.py
Disk.py
from .abstracts import Mountable import os import time import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def _prepare_device(node, devicename): logger.debug("prepare device %s", devicename) ss = devicename.split('/') if len(ss) < 3: raise RuntimeError("bad device name: {}".format(devicename)) name = ss[2] disk = node.disks.get(name) if disk is None: raise ValueError("device {} not found".format(name)) node.client.system('parted -s /dev/{} mklabel gpt mkpart primary 1m 100%'.format(name)).get() now = time.time() # check partitions is ready and writable while now + 60 > time.time(): try: disk = node.disks.get(name) if len(disk.partitions) > 0: partition = disk.partitions[0] resp = node.client.bash('test -b {0} && dd if={0} of=/dev/null bs=4k count=1024'.format(partition.devicename)).get() if resp.state == 'SUCCESS': return partition except: time.sleep(1) continue else: raise RuntimeError("Failed to create partition") class StoragePools: def __init__(self, node): self.node = node self._client = node._client def list(self): storagepools = [] btrfs_list = self._client.btrfs.list() if btrfs_list: for btrfs in self._client.btrfs.list(): if btrfs['label'].startswith('sp_'): name = btrfs['label'].split('_', 1)[1] devicenames = [device['path'] for device in btrfs['devices']] storagepools.append(StoragePool(self.node, name, devicenames)) return storagepools def get(self, name): for pool in self.list(): if pool.name == name: return pool raise ValueError("Could not find StoragePool with name {}".format(name)) def create(self, name, devices, metadata_profile, data_profile, overwrite=False): label = 'sp_{}'.format(name) logger.debug("create storagepool %s", label) device_names = [] for device in devices: part = _prepare_device(self.node, device) device_names.append(part.devicename) self._client.btrfs.create(label, device_names, metadata_profile, data_profile, overwrite=overwrite) pool = StoragePool(self.node, name, device_names) return pool class StoragePool(Mountable): def __init__(self, node, name, devices): self.node = node self._client = node._client self.devices = devices self.name = name self._mountpoint = None self._ays = None @property def devicename(self): return 'UUID={}'.format(self.uuid) def mount(self, target=None): if target is None: target = os.path.join('/mnt/storagepools/{}'.format(self.name)) return super().mount(target) def delete(self, zero=True): """ Destroy storage pool param zero: write zeros (nulls) to the first 500MB of each disk in this storagepool """ if self.mountpoint: self.umount() partitionmap = {} for disk in self.node.disks.list(): for partition in disk.partitions: partitionmap[partition.name] = partition for device in self.devices: diskpath = os.path.basename(device) partition = partitionmap.get(diskpath) if partition: disk = partition.disk self._client.disk.rmpart(disk.name, 1) if zero: self._client.bash('test -b /dev/{0} && dd if=/dev/zero bs=1M count=500 of=/dev/{0}'.format(diskpath)).get() return True return False @property def mountpoint(self): mounts = self.node.list_mounts() for device in self.devices: for mount in mounts: if mount.device == device: options = mount.options.split(',') if 'subvol=/' in options: return mount.mountpoint def is_device_used(self, device): """ check if the device passed as argument is already part of this storagepool @param device: str e.g: /dev/sda """ for d in self.devices: if d.startswith(device): return True return False def device_add(self, *devices): to_add = [] for device in devices: if self.is_device_used(device): continue part = _prepare_device(self.node, device) logger.debug("add device %s to %s", device, self) to_add.append(part.devicename) self._client.btrfs.device_add(self._get_mountpoint(), *to_add) self.devices.extend(to_add) def device_remove(self, *devices): self._client.btrfs.device_remove(self._get_mountpoint(), *devices) for device in devices: if device in self.devices: logger.debug("remove device %s to %s", device, self) self.devices.remove(device) @property def fsinfo(self): if self.mountpoint is None: raise ValueError("can't get fsinfo if storagepool is not mounted") return self._client.btrfs.info(self.mountpoint) @mountpoint.setter def mountpoint(self, value): # do not do anything mountpoint is dynamic return def _get_mountpoint(self): mountpoint = self.mountpoint if not mountpoint: raise RuntimeError("Can not perform action when filesystem is not mounted") return mountpoint @property def info(self): for fs in self._client.btrfs.list(): if fs['label'] == 'sp_{}'.format(self.name): return fs return None def raw_list(self): mountpoint = self._get_mountpoint() return self._client.btrfs.subvol_list(mountpoint) or [] def get_devices_and_status(self): device_map = [] disks = self._client.disk.list()['blockdevices'] pool_status = 'healthy' for device in self.devices: info = None for disk in disks: disk_name = "/dev/%s" % disk['kname'] if device == disk_name and disk['mountpoint']: info = disk break for part in disk.get('children', []) or []: if device == "/dev/%s" % part['kname']: info = part break if info: break status = 'healthy' if info['subsystems'] != 'block:virtio:pci': result = self._client.bash("smartctl -H %s > /dev/null ;echo $?" % disk_name).get() exit_status = int(result.stdout) if exit_status & 1 << 0: status = "unknown" pool_status = 'degraded' if (exit_status & 1 << 2) or (exit_status & 1 << 3): status = 'degraded' pool_status = 'degraded' device_map.append({ 'device': device, 'partUUID': info['partuuid'] or '' if info else '', 'status': status, }) return device_map, pool_status def list(self): subvolumes = [] for subvol in self.raw_list(): path = subvol['Path'] type_, _, name = path.partition('/') if type_ == 'filesystems': subvolumes.append(FileSystem(name, self)) return subvolumes def get(self, name): """ Get Filesystem """ for filesystem in self.list(): if filesystem.name == name: return filesystem raise ValueError("Could not find filesystem with name {}".format(name)) def exists(self, name): """ Check if filesystem with name exists """ for subvolume in self.list(): if subvolume.name == name: return True return False def create(self, name, quota=None): """ Create filesystem """ logger.debug("Create filesystem %s on %s", name, self) mountpoint = self._get_mountpoint() fspath = os.path.join(mountpoint, 'filesystems') self._client.filesystem.mkdir(fspath) subvolpath = os.path.join(fspath, name) self._client.btrfs.subvol_create(subvolpath) if quota: pass return FileSystem(name, self) @property def size(self): total = 0 fs = self.info if fs: for device in fs['devices']: total += device['size'] return total @property def uuid(self): fs = self.info if fs: return fs['uuid'] return None @property def used(self): total = 0 fs = self.info if fs: for device in fs['devices']: total += device['used'] return total @property def ays(self): if self._ays is None: from zeroos.orchestrator.sal.atyourservice.StoragePool import StoragePoolAys self._ays = StoragePoolAys(self) return self._ays def __repr__(self): return "StoragePool <{}>".format(self.name) class FileSystem: def __init__(self, name, pool): self.name = name self.pool = pool self._client = pool.node.client self.subvolume = "filesystems/{}".format(name) self.path = os.path.join(self.pool.mountpoint, self.subvolume) self.snapshotspath = os.path.join(self.pool.mountpoint, 'snapshots', self.name) self._ays = None def delete(self, includesnapshots=True): """ Delete filesystem """ paths = [fs['Path'] for fs in self._client.btrfs.subvol_list(self.path)] paths.sort(reverse=True) for path in paths: rpath = os.path.join(self.path, os.path.relpath(path, self.subvolume)) self._client.btrfs.subvol_delete(rpath) self._client.btrfs.subvol_delete(self.path) if includesnapshots: for snapshot in self.list(): snapshot.delete() self._client.filesystem.remove(self.snapshotspath) def get(self, name): """ Get snapshot """ for snap in self.list(): if snap.name == name: return snap raise ValueError("Could not find snapshot {}".format(name)) def list(self): """ List snapshots """ snapshots = [] if self._client.filesystem.exists(self.snapshotspath): for fileentry in self._client.filesystem.list(self.snapshotspath): if fileentry['is_dir']: snapshots.append(Snapshot(fileentry['name'], self)) return snapshots def exists(self, name): """ Check if a snapshot exists """ return name in self.list() def create(self, name): """ Create snapshot """ logger.debug("create snapshot %s on %s", name, self.pool) snapshot = Snapshot(name, self) if self.exists(name): raise RuntimeError("Snapshot path {} exists.") self._client.filesystem.mkdir(self.snapshotspath) self._client.btrfs.subvol_snapshot(self.path, snapshot.path) return snapshot @property def ays(self): if self._ays is None: from JumpScale.sal.g8os.atyourservice.StoragePool import FileSystemAys self._ays = FileSystemAys(self) return self._ays def __repr__(self): return "FileSystem <{}: {!r}>".format(self.name, self.pool) class Snapshot: def __init__(self, name, filesystem): self.filesystem = filesystem self._client = filesystem.pool.node.client self.name = name self.path = os.path.join(self.filesystem.snapshotspath, name) self.subvolume = "snapshots/{}/{}".format(self.filesystem.name, name) def rollback(self): self.filesystem.delete(False) self._client.btrfs.subvol_snapshot(self.path, self.filesystem.path) def delete(self): self._client.btrfs.subvol_delete(self.path) def __repr__(self): return "Snapshot <{}: {!r}>".format(self.name, self.filesystem)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/StoragePool.py
StoragePool.py
from zerotier.client import Client import netaddr class ZTBootstrap: def __init__(self, token, bootstap_id, grid_id, cidr): self.bootstap_nwid = bootstap_id self.grid_nwid = grid_id self._cidr = cidr # TODO validate format # create client and set the authentication header self._zt = Client() self._zt.set_auth_header("Bearer " + token) def configure_routes(self): for nwid in [self.bootstap_nwid, self.grid_nwid]: resp = self._zt.network.getNetwork(nwid) resp.raise_for_status() nw = resp.json() nw['config']['routes'] = [{'target': self._cidr, 'via': None}] self._zt.network.updateNetwork(nw, nwid).raise_for_status() def list_join_request(self): """ return a list of member that try to access the bootstap network """ resp = self._zt.network.listMembers(id=self.bootstap_nwid) resp.raise_for_status() requests = [] for member in resp.json(): if not member['online'] or member['config']['authorized']: continue requests.append(member) return requests def assign_ip(self, nwid, member, ip=None): """ Assign an Ip address to a member in a certain network @nwid : id of the network @member : member object @ip: ip address to assing to the member, if None take the next free IP in the range """ if ip is None: ip = self._find_free_ip(nwid) member['config']['authorized'] = True member['config']['ipAssignments'] = [ip] resp = self._zt.network.updateMember(member, member['nodeId'], nwid) resp.raise_for_status() return ip def unauthorize_member(self, nwid, member): member['config']['authorized'] = False member['config']['ipAssignments'] = [] resp = self._zt.network.updateMember(member, member['nodeId'], nwid) resp.raise_for_status() def _find_free_ip(self, nwid): resp = self._zt.network.listMembers(nwid) resp.raise_for_status() all_ips = list(netaddr.IPNetwork(self._cidr)) for member in resp.json(): for addr in member['config']['ipAssignments']: all_ips.remove(netaddr.IPAddress(addr)) if len(all_ips) <= 0: raise RuntimeError("No more free ip in the range %s" % self._cidr) return str(all_ips[0]) if __name__ == '__main__': token = '4gE9Cfqw2vFFzCPC1BYaj2mbSpNScxJx' bootstap_nwid = '17d709436c993670' grid_nwid = 'a09acf02336ce8b5' zt = ZTBootstrap(token, bootstap_nwid, grid_nwid, '192.168.10.0/24') from IPython import embed; embed()
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/ZerotierBootstrap.py
ZerotierBootstrap.py
import json from io import BytesIO import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class Containers: def __init__(self, node): self.node = node def list(self): containers = [] for container in self.node.client.container.list().values(): try: containers.append(Container.from_containerinfo(container, self.node)) except ValueError: # skip containers withouth tags pass return containers def get(self, name): containers = list(self.node.client.container.find(name).values()) if not containers: raise LookupError("Could not find container with name {}".format(name)) if len(containers) > 1: raise LookupError("Found more than one containter with name {}".format(name)) return Container.from_containerinfo(containers[0], self.node) def create(self, name, flist, hostname=None, mounts=None, nics=None, host_network=False, ports=None, storage=None, init_processes=None, privileged=False): logger.debug("create container %s", name) container = Container(name, self.node, flist, hostname, mounts, nics, host_network, ports, storage, init_processes, privileged) container.start() return container class Container: """G8SO Container""" def __init__(self, name, node, flist, hostname=None, mounts=None, nics=None, host_network=False, ports=None, storage=None, init_processes=None, privileged=False, identity=None): """ TODO: write doc string filesystems: dict {filesystemObj: target} """ self.name = name self.node = node self.mounts = mounts or {} self.hostname = hostname self.flist = flist self.ports = ports or {} self.nics = nics or [] self.host_network = host_network self.storage = storage self.init_processes = init_processes or [] self._client = None self.privileged = privileged self.identity = identity self._ays = None for nic in self.nics: nic.pop('token', None) if nic.get('config', {}).get('gateway', ''): nic['monitor'] = True @classmethod def from_containerinfo(cls, containerinfo, node): logger.debug("create container from info") arguments = containerinfo['container']['arguments'] if not arguments['tags']: # we don't deal with tagless containers raise ValueError("Could not load containerinfo withouth tags") return cls(arguments['tags'][0], node, arguments['root'], arguments['hostname'], arguments['mount'], arguments['nics'], arguments['host_network'], arguments['port'], arguments['storage'], arguments['privileged'], arguments['identity']) @classmethod def from_ays(cls, service, password=None): logger.debug("create container from service (%s)", service) from .Node import Node node = Node.from_ays(service.parent, password) ports = {} for portmap in service.model.data.ports: source, dest = portmap.split(':') ports[int(source)] = int(dest) nics = [nic.to_dict() for nic in service.model.data.nics] mounts = {} for mount in service.model.data.mounts: fs_service = service.aysrepo.serviceGet('filesystem', mount.filesystem) try: sp = node.storagepools.get(fs_service.parent.name) fs = sp.get(fs_service.name) except KeyError: continue mounts[fs.path] = mount.target container = cls( name=service.name, node=node, mounts=mounts, nics=nics, hostname=service.model.data.hostname, flist=service.model.data.flist, ports=ports, host_network=service.model.data.hostNetworking, storage=service.model.data.storage, init_processes=[p.to_dict() for p in service.model.data.initProcesses], privileged=service.model.data.privileged, identity=service.model.data.identity, ) return container @property def id(self): logger.debug("get container id") info = self.info if info: return info['container']['id'] return @property def info(self): logger.debug("get container info") for containerid, container in self.node.client.container.list().items(): if self.name in (container['container']['arguments']['tags'] or []): container['container']['id'] = int(containerid) return container return @property def client(self): if self._client is None: self._client = self.node.client.container.client(self.id) return self._client def upload_content(self, remote, content): if isinstance(content, str): content = content.encode('utf8') bytes = BytesIO(content) self.client.filesystem.upload(remote, bytes) def download_content(self, remote): buff = BytesIO() self.client.filesystem.download(remote, buff) return buff.getvalue().decode() def _create_container(self, timeout=60): logger.debug("send create container command to g8os") tags = [self.name] if self.hostname and self.hostname != self.name: tags.append(self.hostname) job = self.node.client.container.create( root_url=self.flist, mount=self.mounts, host_network=self.host_network, nics=self.nics, port=self.ports, tags=tags, hostname=self.hostname, storage=self.storage, privileged=self.privileged, identity=self.identity, ) containerid = job.get(timeout) self._client = self.node.client.container.client(containerid) def is_job_running(self, cmd): try: for job in self._client.job.list(): arguments = job['cmd']['arguments'] if 'name' in arguments and arguments['name'] == cmd: return job return False except Exception as err: if str(err).find("invalid container id"): return False raise def is_port_listening(self, port, timeout=60): import time start = time.time() while start + timeout > time.time(): if port not in self.node.freeports(port, nrports=3): return True time.sleep(0.2) return False def start(self): if not self.is_running(): logger.debug("start %s", self) self._create_container() for process in self.init_processes: cmd = "{} {}".format(process['name'], ' '.join(process.get('args', []))) pwd = process.get('pwd', '') stdin = process.get('stdin', '') env = {} for x in process.get('environment', []): k, v = x.split("=") env[k] = v self.client.system(command=cmd, dir=pwd, stdin=stdin, env=env) def stop(self): if not self.is_running(): return logger.debug("stop %s", self) self.node.client.container.terminate(self.id) self._client = None def is_running(self): return self.id is not None @property def ays(self): if self._ays is None: from JumpScale.sal.g8os.atyourservice.StorageCluster import ContainerAYS self._ays = ContainerAYS(self) return self._ays def __str__(self): return "Container <{}>".format(self.name) def __repr__(self): return str(self)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/Container.py
Container.py
from js9 import j import os from zeroos.core0.client.client import Timeout import json import hashlib class HealthCheckObject: def __init__(self, id, name, category, resource): self.id = id self.name = name self.category = category self._messages = [] self.resource = resource self.stacktrace = '' def add_message(self, id, status, text): self._messages.append({'id': id, 'text': text, 'status': status}) def to_dict(self): return { 'id': self.id, 'name': self.name, 'category': self.category, 'resource': self.resource, 'stacktrace': self.stacktrace or '', 'messages': self._messages } class HealthCheckRun(HealthCheckObject): def start(self, *args, **kwargs): try: self.run(*args, **kwargs) except Exception as e: eco = j.errorhandler.parsePythonExceptionObject(e) self.stacktrace = eco.traceback return self.to_dict() class IPMIHealthCheck(HealthCheckRun): def execute_ipmi(self, container, cmd): if self.node.client.filesystem.exists("/dev/ipmi") or self.node.client.filesystem.exists("/dev/ipmi0"): return container.client.system(cmd).get().stdout return '' class ContainerContext: def __init__(self, node, flist): self.node = node self.flist = flist self.container = None self._name = 'healthcheck_{}'.format(hashlib.md5(flist.encode()).hexdigest()) def __enter__(self): try: self.container = self.node.containers.get(self._name) except LookupError: self.container = self.node.containers.create(self._name, self.flist, host_network=True, privileged=True) return self.container def __exit__(self, exc_type, exc_val, exc_tb): return class HealthCheck: def __init__(self, node): self.node = node self.healtcheckfolder = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'healthchecks') def with_container(self, flist): return ContainerContext(self.node, flist) def run(self, container, name, timeout=None): try: healthcheckfile = os.path.join(self.healtcheckfolder, name + '.py') if not os.path.exists(healthcheckfile): raise RuntimeError("Healtcheck with name {} not found".format(name)) container.client.filesystem.upload_file('/tmp/{}.py'.format(name), healthcheckfile) try: job = container.client.bash('python3 /tmp/{}.py'.format(name)) response = job.get(timeout) except Timeout: container.client.job.kill(job.id, 9) raise RuntimeError("Failed to execute {} on time".format(name)) if response.state == 'ERROR': raise RuntimeError("Failed to execute {} {}".format(name, response.stdout)) try: return json.loads(response.stdout) except Exception: raise RuntimeError("Failed to parse response of {}".format(name)) except Exception as e: healtcheck = { 'id': name, 'status': 'ERROR', 'message': str(e) } return healtcheck def cpu_mem(self): from .healthchecks.cpu_mem_core import CPU, Memory cpu = CPU(self.node) memory = Memory(self.node) return [cpu.start(), memory.start()] def disk_usage(self): from .healthchecks.diskusage import DiskUsage usage = DiskUsage(self.node) return usage.start() def network_bond(self): from .healthchecks.networkbond import NetworkBond bond = NetworkBond(self.node) return bond.start() def node_temperature(self, container): from .healthchecks.temperature import Temperature temperature = Temperature(self.node) result = temperature.start(container) return result def network_stability(self, nodes): from .healthchecks.networkstability import NetworkStability stability = NetworkStability(self.node) return stability.start(nodes) def rotate_logs(self): from .healthchecks.log_rotator import RotateLogs rotator = RotateLogs(self.node) return rotator.start() def openfiledescriptors(self): from .healthchecks.openfiledescriptors import OpenFileDescriptor ofd = OpenFileDescriptor(self.node) return ofd.start() def interrupts(self): from .healthchecks.interrupts import Interrupts inter = Interrupts(self.node) return inter.start() def threads(self): from .healthchecks.threads import Threads thread = Threads(self.node) return thread.start() def ssh_cleanup(self, job): from .healthchecks.ssh_cleanup import SSHCleanup cleaner = SSHCleanup(self.node, job) return cleaner.start() def powersupply(self, container): from .healthchecks.powersupply import PowerSupply powersupply = PowerSupply(self.node) return powersupply.start(container) def fan(self, container): from .healthchecks.fan import Fan fan = Fan(self.node) return fan.start(container) def context_switch(self): from .healthchecks.context_switch import ContextSwitch return ContextSwitch(self.node).start() def network_load(self): from .healthchecks.networkload import NetworkLoad load = NetworkLoad(self.node) return load.start()
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/healthcheck.py
healthcheck.py
from zeroos.core0.client import Client from .Disk import Disks, DiskType from .Container import Containers from .StoragePool import StoragePools from .Network import Network from .healthcheck import HealthCheck from collections import namedtuple from datetime import datetime from io import BytesIO import netaddr Mount = namedtuple('Mount', ['device', 'mountpoint', 'fstype', 'options']) class Node: """Represent a G8OS Server""" def __init__(self, addr, port=6379, password=None, timeout=120): # g8os client to talk to the node self._client = Client(host=addr, port=port, password=password, timeout=timeout) self._storageAddr = None self.addr = addr self.port = port self.disks = Disks(self) self.storagepools = StoragePools(self) self.containers = Containers(self) self.network = Network(self) self.healthcheck = HealthCheck(self) @classmethod def from_ays(cls, service, password=None, timeout=120): return cls( addr=service.model.data.redisAddr, port=service.model.data.redisPort, password=password, timeout=timeout ) @property def client(self): return self._client @property def name(self): def get_nic_hwaddr(nics, name): for nic in nics: if nic['name'] == name: return nic['hardwareaddr'] defaultgwdev = self.client.bash("ip route | grep default | awk '{print $5}'").get().stdout.strip() nics = self.client.info.nic() macgwdev = None if defaultgwdev: macgwdev = get_nic_hwaddr(nics, defaultgwdev) if not macgwdev: raise AttributeError("name not find for node {}".format(self)) return macgwdev.replace(":", '') @property def storageAddr(self): if not self._storageAddr: nic_data = self.client.info.nic() for nic in nic_data: if nic['name'] == 'backplane': for ip in nic['addrs']: network = netaddr.IPNetwork(ip['addr']) if network.version == 4: self._storageAddr = network.ip.format() return self._storageAddr self._storageAddr = self.addr return self._storageAddr def get_nic_by_ip(self, addr): try: res = next(nic for nic in self._client.info.nic() if any(addr == a['addr'].split('/')[0] for a in nic['addrs'])) return res except StopIteration: return None def _eligible_fscache_disk(self, disks): """ return the first disk that is eligible to be used as filesystem cache First try to find a SSH disk, otherwise return a HDD """ priorities = [DiskType.ssd, DiskType.hdd, DiskType.nvme] eligible = {t: [] for t in priorities} # Pick up the first ssd usedisks = [] for pool in (self._client.btrfs.list() or []): for device in pool['devices']: usedisks.append(device['path']) for disk in disks[::-1]: if disk.devicename in usedisks or len(disk.partitions) > 0: continue if disk.type in priorities: eligible[disk.type].append(disk) # pick up the first disk according to priorities for t in priorities: if eligible[t]: return eligible[t][0] else: raise RuntimeError("cannot find eligible disks for the fs cache") def _mount_fscache(self, storagepool): """ mount the fscache storage pool and copy the content of the in memmory fs inside """ mountedpaths = [mount.mountpoint for mount in self.list_mounts()] containerpath = '/var/cache/containers' if containerpath not in mountedpaths: if storagepool.exists('containercache'): storagepool.get('containercache').delete() fs = storagepool.create('containercache') self.client.disk.mount(storagepool.devicename, containerpath, ['subvol={}'.format(fs.subvolume)]) logpath = '/var/log' if logpath not in mountedpaths: # logs is empty filesystem which we create a snapshot on to store logs of current boot snapname = '{:%Y-%m-%d-%H-%M}'.format(datetime.now()) fs = storagepool.get('logs') snapshot = fs.create(snapname) self.client.bash('mkdir /tmp/log && mv /var/log/* /tmp/log/') self.client.disk.mount(storagepool.devicename, logpath, ['subvol={}'.format(snapshot.subvolume)]) self.client.bash('mv /tmp/log/* /var/log/').get() self.client.logger.reopen() # startup syslogd and klogd self.client.system('syslogd -n -O /var/log/messages') self.client.system('klogd -n') def freeports(self, baseport=2000, nrports=3): ports = self.client.info.port() usedports = set() for portInfo in ports: if portInfo['network'] != "tcp": continue usedports.add(portInfo['port']) freeports = [] while True: if baseport not in usedports: freeports.append(baseport) if len(freeports) >= nrports: return freeports baseport += 1 def find_persistance(self, name='fscache'): fscache_sp = None for sp in self.storagepools.list(): if sp.name == name: fscache_sp = sp break return fscache_sp def ensure_persistance(self, name='fscache'): """ look for a disk not used, create a partition and mount it to be used as cache for the g8ufs set the label `fs_cache` to the partition """ disks = self.disks.list() if len(disks) <= 0: # if no disks, we can't do anything return # check if there is already a storage pool with the fs_cache label fscache_sp = self.find_persistance(name) # create the storage pool if we don't have one yet if fscache_sp is None: disk = self._eligible_fscache_disk(disks) fscache_sp = self.storagepools.create(name, devices=[disk.devicename], metadata_profile='single', data_profile='single', overwrite=True) fscache_sp.mount() try: fscache_sp.get('logs') except ValueError: fscache_sp.create('logs') # mount the storage pool self._mount_fscache(fscache_sp) return fscache_sp def download_content(self, remote): buff = BytesIO() self.client.filesystem.download(remote, buff) return buff.getvalue().decode() def upload_content(self, remote, content): if isinstance(content, str): content = content.encode('utf8') bytes = BytesIO(content) self.client.filesystem.upload(remote, bytes) def wipedisks(self): print('Wiping node {hostname}'.format(**self.client.info.os())) mounteddevices = {mount['device']: mount for mount in self.client.info.disk()} def getmountpoint(device): for mounteddevice, mount in mounteddevices.items(): if mounteddevice.startswith(device): return mount jobs = [] for disk in self.client.disk.list()['blockdevices']: devicename = '/dev/{}'.format(disk['kname']) mount = getmountpoint(devicename) if not mount: print(' * Wiping disk {kname}'.format(**disk)) jobs.append(self.client.system('dd if=/dev/zero of={} bs=1M count=50'.format(devicename))) else: print(' * Not wiping {device} mounted at {mountpoint}'.format(device=devicename, mountpoint=mount['mountpoint'])) # wait for wiping to complete for job in jobs: job.get() def list_mounts(self): allmounts = [] for mount in self.client.info.disk(): allmounts.append(Mount(mount['device'], mount['mountpoint'], mount['fstype'], mount['opts'])) return allmounts def __str__(self): return "Node <{host}:{port}>".format( host=self.addr, port=self.port, ) def __repr__(self): return str(self) def __eq__(self, other): a = "{}:{}".format(self.addr, self.port) b = "{}:{}".format(other.addr, other.port) return a == b def __hash__(self): return hash((self.addr, self.port))
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/Node.py
Node.py
import ssl import json import aioredis import sys import uuid import time import logging import asyncio logger = logging.getLogger('g8core') class Response: def __init__(self, client, id): self._client = client self._id = id self._queue = 'result:{}'.format(id) async def exists(self): r = self._client._redis flag = '{}:flag'.format(self._queue) key_exists = await r.connection.execute('LKEYEXISTS', flag) return bool(key_exists) async def get(self, timeout=None): if timeout is None: timeout = self._client.timeout r = self._client._redis start = time.time() maxwait = timeout while maxwait > 0: job_exists = await self.exists() if not job_exists: raise RuntimeError("Job not found: %s" % self.id) v = await r.brpoplpush(self._queue, self._queue, min(maxwait, 10)) if v is not None: return json.loads(v.decode()) logger.debug('%s still waiting (%ss)', self._id, int(time.time() - start)) maxwait -= 10 raise TimeoutError() class Pubsub: def __init__(self, loop, host, port=6379, password="", db=0, ctx=None, timeout=None, testConnectionAttempts=3, callback=None): socket_timeout = (timeout + 5) if timeout else 15 self.testConnectionAttempts = testConnectionAttempts self._redis = None self.host = host self.port = port self.password = password self.db = db if ctx is None: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE self.ssl = ctx self.timeout = socket_timeout self.loop = loop async def default_callback(job_id, level, line, meta): w = sys.stdout if level == 1 else sys.stderr w.write(line) w.write('\n') self.callback = callback or default_callback if not callable(self.callback): raise Exception('callback must be callable') async def get(self): if self._redis is not None: return self._redis self._redis = await aioredis.create_redis((self.host, self.port), loop=self.loop, password=self.password, db=self.db, ssl=self.ssl, timeout=self.timeout) return self._redis async def global_stream(self, queue, timeout=120): if self._redis.connection.closed: self._redis = await self.get() data = await asyncio.wait_for(self._redis.blpop(queue, timeout=timeout), timeout=timeout) _, body = data payload = json.loads(body.decode()) message = payload['message'] line = message['message'] meta = message['meta'] job_id = payload['command'] await self.callback(job_id, meta >> 16, line, meta & 0xff) async def raw(self, command, arguments, queue=None, max_time=None, stream=False, tags=None, id=None): if not id: id = str(uuid.uuid4()) payload = { 'id': id, 'command': command, 'arguments': arguments, 'queue': queue, 'max_time': max_time, 'stream': stream, 'tags': tags, } self._redis = await self.get() flag = 'result:{}:flag'.format(id) await self._redis.rpush('core:default', json.dumps(payload)) if await self._redis.brpoplpush(flag, flag, 10) is None: raise TimeoutError('failed to queue job {}'.format(id)) logger.debug('%s >> g8core.%s(%s)', id, command, ', '.join(("%s=%s" % (k, v) for k, v in arguments.items()))) return Response(self, id) async def sync(self, command, args): response = await self.raw(command, args) result = await response.get() if result["state"] != 'SUCCESS': raise RuntimeError('invalid response: %s' % result["state"]) return json.loads(result["data"]) async def ping(self): response = await self.sync('core.ping', {}) return response async def subscribe(self, queue=None): response = await self.sync('logger.subscribe', {'queue': queue}) return response
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/Pubsub.py
Pubsub.py
import io import time import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class StorageEngine: """storageEngine server""" def __init__(self, name, container, bind='0.0.0.0:16379', data_dir='/mnt/data', master=None): """ TODO: write doc string """ self.name = name self.master = master self.container = container self.bind = bind self.port = int(bind.split(':')[1]) self.data_dir = data_dir self.master = master self._ays = None @classmethod def from_ays(cls, service, password=None): logger.debug("create storageEngine from service (%s)", service) from .Container import Container container = Container.from_ays(service.parent, password) if service.model.data.master != '': master_service = service.aysrepo.serviceGet('storage_engine', service.model.data.master) master = StorageEngine.from_ays(master_service, password) else: master = None return cls( name=service.name, container=container, bind=service.model.data.bind, data_dir=service.model.data.homeDir, master=master, ) def _configure(self): logger.debug("configure storageEngine") buff = io.BytesIO() self.container.client.filesystem.download('/etc/ardb.conf', buff) content = buff.getvalue().decode() # update config content = content.replace('/mnt/data', self.data_dir) content = content.replace('0.0.0.0:16379', self.bind) mgmt_bind = "%s:%s" % (self.container.node.addr, self.port) if self.bind != mgmt_bind: content += "server[1].listen %s\n" % mgmt_bind if self.master is not None: _, port = self.master.bind.split(":") content = content.replace('#slaveof 127.0.0.1:6379', 'slaveof {}:{}'.format(self.master.container.node.addr, port)) # make sure home directory exists self.container.client.filesystem.mkdir(self.data_dir) # upload new config self.container.client.filesystem.upload('/etc/ardb.conf.used', io.BytesIO(initial_bytes=content.encode())) def start(self, timeout=100): if not self.container.is_running(): self.container.start() running, _ = self.is_running() if running: return logger.debug('start %s', self) self._configure() self.container.client.system('/bin/ardb-server /etc/ardb.conf.used', id="{}.{}".format("storage_engine", self.name)) # wait for storageEngine to start start = time.time() end = start + timeout is_running, _ = self.is_running() while not is_running and time.time() < end: time.sleep(1) is_running, _ = self.is_running() if not is_running: raise RuntimeError("storage server {} didn't started".format(self.name)) def stop(self, timeout=30): if not self.container.is_running(): return is_running, job = self.is_running() if not is_running: return logger.debug('stop %s', self) self.container.client.job.kill(job['cmd']['id']) # wait for StorageEngine to stop start = time.time() end = start + timeout is_running, _ = self.is_running() while is_running and time.time() < end: time.sleep(1) is_running, _ = self.is_running() if is_running: raise RuntimeError("storage server {} didn't stopped") def is_healthy(self): import redis client = redis.Redis(self.container.node.addr, self.port) key = "keytest" value = b"some test value" if not client.set(key, value): return False result = client.get(key) if result != value: return False client.delete(key) if client.exists(key): return False return True def is_running(self): try: if self.port not in self.container.node.freeports(self.port, 1): for job in self.container.client.job.list(): if 'name' in job['cmd']['arguments'] and job['cmd']['arguments']['name'] == '/bin/ardb-server': return (True, job) return (False, None) except Exception as err: if str(err).find("invalid container id"): return (False, None) raise @property def ays(self): if self._ays is None: from JumpScale.sal.g8os.atyourservice.StorageCluster import storageEngineAys self._ays = storageEngineAys(self) return self._ays def __str__(self): return "storageEngine <{}>".format(self.name) def __repr__(self): return str(self)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/StorageEngine.py
StorageEngine.py
from io import BytesIO import logging import yaml logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class EtcdCluster: """etced server""" def __init__(self, name, dialstrings): self.name = name self.dialstrings = dialstrings self._ays = None @classmethod def from_ays(cls, service, password=None): logger.debug("create storageEngine from service (%s)", service) dialstrings = set() for etcd_service in service.producers.get('etcd', []): etcd = ETCD.from_ays(etcd_service, password) dialstrings.add(etcd.clientBind) return cls( name=service.name, dialstrings=",".join(dialstrings), ) class ETCD: """etced server""" def __init__(self, name, container, serverBind, clientBind, peers, data_dir='/mnt/data'): self.name = name self.container = container self.serverBind = serverBind self.clientBind = clientBind self.data_dir = data_dir self.peers = ",".join(peers) self._ays = None @classmethod def from_ays(cls, service, password=None): logger.debug("create storageEngine from service (%s)", service) from .Container import Container container = Container.from_ays(service.parent, password) return cls( name=service.name, container=container, serverBind=service.model.data.serverBind, clientBind=service.model.data.clientBind, data_dir=service.model.data.homeDir, peers=service.model.data.peers, ) def start(self): configpath = "/etc/etcd_{}.config".format(self.name) config = { "name": self.name, "initial-advertise-peer-urls": "http://{}".format(self.serverBind), "listen-peer-urls": "http://{}".format(self.serverBind), "listen-client-urls": "http://{}".format(self.clientBind), "advertise-client-urls": "http://{}".format(self.clientBind), "initial-cluster": self.peers, "data-dir": self.data_dir, "initial-cluster-state": "new" } yamlconfig = yaml.safe_dump(config, default_flow_style=False) configstream = BytesIO(yamlconfig.encode('utf8')) configstream.seek(0) self.container.client.filesystem.upload(configpath, configstream) cmd = '/bin/etcd --config-file %s' % configpath self.container.client.system(cmd, id="etcd.{}".format(self.name)) if not self.container.is_port_listening(int(self.serverBind.split(":")[1])): raise RuntimeError('Failed to start etcd server: {}'.format(self.name)) def put(self, key, value): if value.startswith("-"): value = "-- %s" % value if key.startswith("-"): key = "-- %s" % key cmd = '/bin/etcdctl \ --endpoints {etcd} \ put {key} "{value}"'.format(etcd=self.clientBind, key=key, value=value) return self.container.client.system(cmd, env={"ETCDCTL_API": "3"}).get()
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/ETCD.py
ETCD.py
import json from js9 import j from .StorageEngine import StorageEngine import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class StorageCluster: """StorageCluster is a cluster of StorageEngine servers""" def __init__(self, label, nodes=None, disk_type=None): """ @param label: string repsenting the name of the storage cluster """ self.label = label self.name = label self.nodes = nodes or [] self.filesystems = [] self.storage_servers = [] self.disk_type = disk_type self.k = 0 self.m = 0 self._ays = None @classmethod def from_ays(cls, service, password): logger.debug("load cluster storage cluster from service (%s)", service) disk_type = str(service.model.data.diskType) nodes = [] storage_servers = [] for storageEngine_service in service.producers.get('storage_engine', []): storages_server = StorageServer.from_ays(storageEngine_service, password) storage_servers.append(storages_server) if storages_server.node not in nodes: nodes.append(storages_server.node) cluster = cls(label=service.name, nodes=nodes, disk_type=disk_type) cluster.storage_servers = storage_servers cluster.k = service.model.data.k cluster.m = service.model.data.m return cluster @property def dashboard(self): board = StorageDashboard(self) return board.template def get_config(self): data = {'dataStorage': [], 'metadataStorage': None, 'label': self.name, 'status': 'ready' if self.is_running() else 'error', 'nodes': [node.name for node in self.nodes]} for storageserver in self.storage_servers: if 'metadata' in storageserver.name: data['metadataStorage'] = {'address': storageserver.storageEngine.bind} else: data['dataStorage'].append({'address': storageserver.storageEngine.bind}) return data @property def nr_server(self): """ Number of storage server part of this cluster """ return len(self.storage_servers) def find_disks(self): """ return a list of disk that are not used by storage pool or has a different type as the one required for this cluster """ logger.debug("find available_disks") cluster_name = 'sp_cluster_{}'.format(self.label) available_disks = {} def check_partition(disk): for partition in disk.partitions: for filesystem in partition.filesystems: if filesystem['label'].startswith(cluster_name): return True for node in self.nodes: for disk in node.disks.list(): # skip disks of wrong type if disk.type.name != self.disk_type: continue # skip devices which have filesystems on the device if len(disk.filesystems) > 0: continue # include devices which have partitions if len(disk.partitions) == 0: available_disks.setdefault(node.name, []).append(disk) else: if check_partition(disk): # devices that have partitions with correct label will be in the beginning available_disks.setdefault(node.name, []).insert(0, disk) return available_disks def start(self): logger.debug("start %s", self) for server in self.storage_servers: server.start() def stop(self): logger.debug("stop %s", self) for server in self.storage_servers: server.stop() def is_running(self): # TODO: Improve this, what about part of server running and part stopped for server in self.storage_servers: if not server.is_running(): return False return True def health(self): """ Return a view of the state all storage server running in this cluster example : { 'cluster1_1': {'storageEngine': True, 'container': True}, 'cluster1_2': {'storageEngine': True, 'container': True}, } """ health = {} for server in self.storage_servers: running, _ = server.storageEngine.is_running() health[server.name] = { 'storageEngine': running, 'container': server.container.is_running(), } return health def __str__(self): return "StorageCluster <{}>".format(self.label) def __repr__(self): return str(self) class StorageServer: """StorageEngine servers""" def __init__(self, cluster): self.cluster = cluster self.container = None self.storageEngine = None @classmethod def from_ays(cls, storageEngine_services, password=None): storageEngine = StorageEngine.from_ays(storageEngine_services, password) storage_server = cls(None) storage_server.container = storageEngine.container storage_server.storageEngine = storageEngine return storage_server @property def name(self): if self.storageEngine: return self.storageEngine.name return None @property def node(self): if self.container: return self.container.node return None def _find_port(self, start_port=2000): while True: if j.sal.nettools.tcpPortConnectionTest(self.node.addr, start_port, timeout=2): start_port += 1 continue return start_port def start(self, timeout=30): logger.debug("start %s", self) if not self.container.is_running(): self.container.start() ip, port = self.storageEngine.bind.split(":") self.storageEngine.bind = '{}:{}'.format(ip, self._find_port(port)) self.storageEngine.start(timeout=timeout) def stop(self, timeout=30): logger.debug("stop %s", self) self.storageEngine.stop(timeout=timeout) self.container.stop() def is_running(self): container = self.container.is_running() storageEngine, _ = self.storageEngine.is_running() return (container and storageEngine) def __str__(self): return "StorageServer <{}>".format(self.container.name) def __repr__(self): return str(self) class StorageDashboard: def __init__(self, cluster): self.cluster = cluster self.store = 'statsdb' def build_templating(self): templating = { "list": [], "rows": [] } return templating def dashboard_template(self): return { "annotations": { "list": [] }, "editable": True, "gnetId": None, "graphTooltip": 0, "hideControls": False, "id": None, "links": [], "rows": [], "schemaVersion": 14, "style": "dark", "tags": [], "time": { "from": "now/d", "to": "now" }, "timepicker": { "refresh_intervals": [ "5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ], "time_options": [ "5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d" ] }, "timezone": "", "title": self.cluster.name, "version": 8 } def build_row(self, panel): template = { "collapse": False, "height": 295, "panels": [], "repeat": None, "repeatIteration": None, "repeatRowId": None, "showTitle": False, "title": "Dashboard Row", "titleSize": "h6" } template["panels"] += panel return template def build_panel(self, title, target, panel_id, unit): template = { "aliasColors": {}, "bars": False, "dashLength": 10, "dashes": False, "datasource": self.store, "fill": 1, "id": panel_id, "legend": { "avg": False, "current": False, "max": False, "min": False, "show": True, "total": False, "values": False }, "lines": True, "linewidth": 1, "links": [], "nullPointMode": "null", "percentage": False, "pointradius": 5, "points": False, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "span": 6, "stack": True, "steppedLine": False, "targets": [], "thresholds": [], "timeFrom": None, "timeShift": None, "tooltip": { "shared": True, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": None, "mode": "time", "name": None, "show": True, "values": [] }, "yaxes": [ { "format": unit, "label": None, "logBase": 1, "max": None, "min": None, "show": True }, { "format": "short", "label": None, "logBase": 1, "max": None, "min": None, "show": True } ] } template["title"] = title template["targets"].append(target) return template def build_target(self, measurement, disks): template = { "alias": "$tag_node/$tag_id", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "node" ], "type": "tag" }, { "params": [ "id" ], "type": "tag" }, { "params": [ "none" ], "type": "fill" } ], "orderByTime": "ASC", "policy": "default", "rawQuery": False, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [ { "key": "type", "operator": "=", "value": "phys" } ] } template["measurement"] = measurement for idx, disk in enumerate(disks): tag = [ { "key": "node", "operator": "=", "value": disk.split("_")[0] }, { "condition": "AND", "key": "id", "operator": "=", "value": disk.split("_")[1] } ] if idx == 0: tag[0]["condition"] = "AND" else: tag[0]["condition"] = "OR" template["tags"] += tag return template @property def template(self): AGGREGATED_CONFIG = { "Aggregated read IOPs": "disk.iops.read|m", "Aggregated write IOPs": "disk.iops.write|m", "Aggregated free size": "disk.size.free|m", } panel_id = 1 disks = set() for server in self.cluster.storage_servers: server = server.name.split("_") disks.add("{}_{}".format(server[1], server[-3])) disks = list(disks) panels = [] for title, measurement in AGGREGATED_CONFIG.items(): if 'size' in title: partitions = [disk+'1' for disk in disks] target = self.build_target(measurement, partitions) panels.append(self.build_panel(title, target, panel_id, "decbytes")) else: target = self.build_target(measurement, disks) panels.append(self.build_panel(title, target, panel_id, "iops")) panel_id += 1 for disk in disks: target = self.build_target("disk.iops.read|m", [disk]) panels.append(self.build_panel("Read IOPs", target, panel_id, "iops")) panel_id += 1 target = self.build_target("disk.iops.write|m", [disk]) panels.append(self.build_panel("Write IOPs", target, panel_id, "iops")) panel_id += 1 target = self.build_target("disk.size.free|m", [disk+'1']) panels.append(self.build_panel("Free size", target, panel_id, "decbytes")) panel_id += 1 template = self.dashboard_template() for idx, panel in enumerate(panels): if idx % 2 == 0: row = self.build_row(panels[idx:idx+2]) template["rows"].append(row) template = json.dumps(template) return template
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/StorageCluster.py
StorageCluster.py
from ..abstracts import AYSable from js9 import j class StoragePoolAys(AYSable): def __init__(self, storagepool): self._obj = storagepool self.actor = 'storagepool' def create(self, aysrepo): try: service = aysrepo.serviceGet(role='storagepool', instance=self._obj.name) except j.exceptions.NotFound: service = None device_map, pool_status = self._obj.get_devices_and_status() if service is None: # create new service actor = aysrepo.actorGet(self.actor) args = { 'metadataProfile': self._obj.fsinfo['metadata']['profile'], 'dataProfile': self._obj.fsinfo['data']['profile'], 'devices': device_map, 'node': self._node_name, 'status': pool_status, } service = actor.serviceCreate(instance=self._obj.name, args=args) else: # update model on exists service service.model.data.init('devices', len(device_map)) for i, device in enumerate(device_map): service.model.data.devices[i] = device service.model.data.status = pool_status service.saveAll() return service @property def _node_name(self): def is_valid_nic(nic): for exclude in ['zt', 'core', 'kvm', 'lo']: if nic['name'].startswith(exclude): return False return True for nic in filter(is_valid_nic, self._obj.node.client.info.nic()): if len(nic['addrs']) > 0 and nic['addrs'][0]['addr'] != '': return nic['hardwareaddr'].replace(':', '') raise AttributeError("name not find for node {}".format(self._obj.node)) class FileSystemAys(AYSable): def __init__(self, filesystem): self._obj = filesystem self.actor = 'filesystem' def create(self, aysrepo): actor = aysrepo.actorGet(self.actor) args = { 'storagePool': self._obj.pool.name, 'name': self._obj.name, # 'readOnly': ,FIXME # 'quota': ,FIXME } return actor.serviceCreate(instance=self._obj.name, args=args)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/atyourservice/StoragePool.py
StoragePool.py
import re import os import datetime from ..healthcheck import HealthCheckRun descr = """ Rotate know log files if their size hit 10G or more """ class RotateLogs(HealthCheckRun): def __init__(self, node): resource = '/nodes/{}'.format(node.name) super().__init__('log-rotator', 'Log Rotator', 'System Load', resource) self.node = node def run(self, locations=['/var/log'], limit=10): message = { 'id': 'log-rotator', 'status': 'OK', 'text': 'Logs did not reach {limit}G'.format(limit=limit) } if "/var/log" not in locations: locations.append("/var/log") logs = [] try: # Get total size for all log files log_size = get_log_size(self.node, locations) # Rotate logs if they are larger than the limit if log_size/(1024 * 1024 * 1024) >= limit: # convert bytes to GIGA # Rotate core.log for location in locations: # Get Files for this location location_files = get_files(self.node, location, []) logs.extend(location_files) for file_path in logs: if file_path == '/var/log/core.log': continue # Delete old rotated files to free up some space # match file.*.date.time if re.match(".*\d{8}-\d{6}", file_path): self.node.client.filesystem.remove(file_path) else: new_path = "%s.%s" % (file_path, datetime.datetime.now().strftime('%Y%m%d-%H%M%S')) # Rotate the new logs self.node.client.filesystem.move(file_path, new_path) # Create a new EMPTY file with the same name fd = self.node.client.filesystem.open(file_path, 'x') self.node.client.filesystem.close(fd) self.node.client.logger.reopen() message['text'] = 'Logs cleared' except Exception as e: message['text'] = "Error happened, Can not clear logs" message['status'] = "ERROR" self.add_message(**message) def get_files(node, location, files=[]): for item in node.client.filesystem.list(location): if not item['is_dir']: files.append(os.path.join(location, item['name'])) else: files = get_files(node, os.path.join(location, item['name']), files) return files def get_log_size(node, locations): size = 0 for location in locations: items = node.client.filesystem.list(location) for item in items: size += item['size'] return size
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/healthchecks/log_rotator.py
log_rotator.py
import re from ..healthcheck import HealthCheckRun descr = """ Monitors if a network bond (if there is one) has both (or more) interfaces properly active. """ class NetworkStability(HealthCheckRun): def __init__(self, node): resource = '/nodes/{}'.format(node.name) super().__init__('networkstability', 'Network Stability Check', 'Network',resource) self.node = node def run(self, nodes): nic = self.node.get_nic_by_ip(self.node.addr) if nic is None: raise LookupError("Couldn't get the management nic") jobs = [] for node in nodes: other_nic = node.get_nic_by_ip(node.addr) if other_nic is not None: if nic['mtu'] != other_nic['mtu']: self.add_message('{}_mtu'.format(node.name), 'ERROR', 'The management interface has mtu {} which is different than node {} which is {}'.format(nic['mtu'], node.name, other_nic['mtu'])) else: self.add_message('{}_mtu'.format(node.name), 'OK', 'The management interface has mtu {} is the same as node {}'.format(nic['mtu'], node.name, other_nic['mtu'])) else: self.add_message('{}_mtu'.format(node.name), 'ERROR', "Couldn't get the management nic for node {}".format(node.name)) jobs.append(self.node.client.system('ping -I {} -c 10 -W 1 -q {}'.format(self.node.addr, node.addr), max_time=20)) for node, job in zip(nodes, jobs): res = job.get().stdout.split('\n') perc = 100 - int(res[2].split(',')[-1].strip().split()[0][:-1]) if perc < 70: self.add_message('{}_ping_perc'.format(node.name), 'ERROR', "Can reach node {} with percentage {}".format(node.name, perc)) elif perc < 90: self.add_message('{}_ping_perc'.format(node.name), 'WARNING', "Can reach node {} with percentage {}".format(node.name, perc)) else: self.add_message('{}_ping_perc'.format(node.name), 'OK', "Can reach node {} with percentage {}".format(node.name, perc)) if perc == 0: self.add_message('{}_ping_rt'.format(node.name), 'ERROR', "Can't reach node {}".format(node.name)) else: rt = float(res[3].split('/')[3]) if rt > 200: self.add_message('{}_ping_rt'.format(node.name), 'ERROR', "Round-trip time to node {} is {}".format(node.name, rt)) elif rt > 10: self.add_message('{}_ping_rt'.format(node.name), 'WARNING', "Round-trip time to node {} is {}".format(node.name, rt)) else: self.add_message('{}_ping_rt'.format(node.name), 'OK', "Round-trip time to node {} is {}".format(node.name, rt))
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/healthchecks/networkstability.py
networkstability.py
from ..healthcheck import IPMIHealthCheck descr = """ Checks temperature of the system. Result will be shown in the "Temperature" section of the Grid Portal / Status Overview / Node Status page. """ class Temperature(IPMIHealthCheck): WARNING_TRIPPOINT = 70 ERROR_TRIPPOINT = 90 def __init__(self, node): self.node = node resource = '/nodes/{}'.format(node.name) super().__init__('temperature', 'Node Temperature Check', 'Hardware', resource) def run(self, container): out = self.execute_ipmi(container, "ipmitool sdr type 'Temp'") if out: if out: # SAMPLE: # root@du-conv-3-01:~# ipmitool sdr type "Temp" # Temp | 0Eh | ok | 3.1 | 37 degrees C # Temp | 0Fh | ok | 3.2 | 34 degrees C # Inlet Temp | B1h | ok | 64.96 | 28 degrees C # Exhaust Temp | B2h | ns | 144.96 | Disabled for line in out.splitlines(): if "|" in line: parts = [part.strip() for part in line.split("|")] id_, sensorstatus, message = parts[0], parts[2], parts[-1] if sensorstatus == "ns" and "no reading" in message.lower(): continue if sensorstatus != "ok" and "no reading" not in message.lower(): self.add_message(**self.get_message(sensor=id_, status='WARNING', message=message)) continue temperature = int(message.split(" ", 1)[0]) self.add_message(**self.get_message(sensor=id_, status=sensorstatus, message=message, temperature=temperature)) else: self.add_message(**self.get_message(status="SKIPPED", message="NO temp information available")) def get_message(self, sensor="", status='OK', message='', temperature=0): result = { "status": status.upper(), "text": "%s: %s" % (sensor, message), "id": sensor, } if status != "OK": return result if temperature >= self.WARNING_TRIPPOINT: result["status"] = "WARNING" elif temperature >= self.ERROR_TRIPPOINT: result["status"] = "ERROR" return result
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/healthchecks/temperature.py
temperature.py
from ..healthcheck import HealthCheckRun from js9 import j descr = """ Clean up ssh deamons and tcp services from migration """ class SSHCleanup(HealthCheckRun): def __init__(self, node, job): resource = '/nodes/{}'.format(node.name) super().__init__('ssh-cleanup', 'SSH Cleanup', 'System Load', resource) self.node = node self.service = job.service self.job = job def run(self): status = 'OK' text = 'Migration Cleanup Succesful' finished = [] try: for job in self.service.aysrepo.jobsList(): job_dict = job.to_dict() if job_dict['actionName'] == 'processChange' and job_dict['actorName'] == 'vm': if job_dict['state'] == 'running': continue vm = self.service.aysrepo.serviceGet(instance=job_dict['serviceName'], role=job_dict['actorName']) finished.append("ssh.config_%s" % vm.name) for proc in self.node.client.process.list(): for partial in finished: if partial not in proc['cmdline']: continue config_file = proc['cmdline'].split()[-1] port = config_file.split('_')[-1] self.node.client.process.kill(proc['pid']) tcp_name = "tcp_%s_%s" % (self.node.name, port) tcp_service = self.service.aysrepo.serviceGet(role='tcp', instance=tcp_name) j.tools.async.wrappers.sync(tcp_service.executeAction("drop"), context=self.job.context) tcp_service.delete() if self.node.client.filesystem.exists('/tmp'): self.node.client.filesystem.remove(config_file) except Exception as e: text = "Error happened, Can not clean ssh process " status = "ERROR" self.add_message(self.id, status, text)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/healthchecks/ssh_cleanup.py
ssh_cleanup.py
from ..healthcheck import IPMIHealthCheck descr = """ Checks the power redundancy of a node using IPMItool. Result will be shown in the "Hardware" section of the Grid Portal / Status Overview / Node Status page. """ class PowerSupply(IPMIHealthCheck): def __init__(self, node): resource = '/nodes/{}'.format(node.name) super().__init__(id='pw-supply', name='Power Supply', category="Hardware", resource=resource) self.node = node self.ps_errmsgs = [ "Power Supply AC lost", "Failure detected", "Predictive failure", "AC lost or out-of-range", "AC out-of-range, but present", "Config Erro", "Power Supply Inactive"] def run(self, container): ps_errmsgs = [x.lower() for x in self.ps_errmsgs if x.strip()] linehaserrmsg = lambda line: any([x in line.lower() for x in ps_errmsgs]) out = self.execute_ipmi(container, """ipmitool -c sdr type "Power Supply" """) if out: # SAMPLE 1: # root@du-conv-3-01:~# ipmitool -c sdr type "Power Supply" # PS1 Status , C8h , ok , 10.1 , Presence detected # PS2 Status,C9h , ok , 10.2 , Presence detected # SAMPLE 2: # root@stor-04:~# ipmitool -c sdr type "Power Supply" # PSU1_Status , DEh , ok , 10.1 , Presence detected # PSU2_Status , DFh , ns , 10.2 , No Reading # PSU3_Status , E0h , ok , 10.3 , Presence detected # PSU4_Status , E1h , ns , 10.4 , No Reading # PSU Redundancy , E6h , ok , 21.1 , Fully Redundant # SAMPLE 3: # root@stor-01:~# ipmitool -c sdr type "Power Supply" # PSU1_Status , DEh , ok , 10.1 , Presence detected , Power Supply AC lost # PSU2_Status , DFh , ns , 10.2 , No Reading # PSU3_Status , E0h , ok , 10.3 , Presence detected # PSU4_Status , E1h , ok , 10.4 , Presence detected # PSU Redundancy , E6h , ok , 21.1 , Redundancy Lost # PSU Alert , 16h , ns , 208.1 , Event-Only psu_redun_in_out = "PSU Redundancy".lower() in out.lower() is_fully_redundant = True if "fully redundant" in out.lower() else False for line in out.splitlines(): if "status" in line.lower(): parts = [part.strip() for part in line.split(",")] id_, presence = parts[0], parts[-1] id_ = id_.strip("Status").strip("_").strip() # clean the power supply name. if linehaserrmsg(line): if psu_redun_in_out and is_fully_redundant: self.add_message(id=id_, status='SKIPPED', text="Power redundancy problem on %s (%s)" % (id_, presence)) else: self.add_message(id=id_, status='WARNING', text="Power redundancy problem on %s (%s)" % (id_, presence)) else: self.add_message(id=id_, status='OK', text="Power supply %s is OK" % id_) else: self.add_message(id="SKIPPED", status='SKIPPED', text="No data for Power Supplies")
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/healthchecks/powersupply.py
powersupply.py
from js9 import j from ..healthcheck import HealthCheckRun descr = """ Checks average memory and CPU usage/load. If average per hour is higher than expected an error condition is thrown. For both memory and CPU usage throws WARNING if more than 80% used and throws ERROR if more than 95% used. Result will be shown in the "System Load" section of the Grid Portal / Status Overview / Node Status page. """ class Memory(HealthCheckRun): def __init__(self, node): resource = '/nodes/{}'.format(node.name) super().__init__('memory', 'Memory', 'System Load', resource) self.node = node def run(self): total_mem = self.node.client.info.mem()['total']/(1024*1024) mem_history = self.node.client.aggregator.query('machine.memory.ram.available').get('machine.memory.ram.available', {}).get('history', {}) if '3600' not in mem_history: self.add_message('MEMORY', 'WARNING', 'Average memory load is not collected yet') else: avg_available_mem = mem_history['3600'][-1]['avg'] avg_used_mem = total_mem - avg_available_mem avg_mem_percent = avg_used_mem/float(total_mem) * 100 self.add_message(**get_message('memory', avg_mem_percent)) class CPU(HealthCheckRun): def __init__(self, node): resource = '/nodes/{}'.format(node.name) super().__init__('CPU', 'CPU', 'System Load', resource) self.node = node def run(self): cpu_percent = 0 count = 0 cpu_usage = self.node.client.aggregator.query('machine.CPU.percent') for cpu, data in cpu_usage.items(): if '3600' not in data['history']: continue cpu_percent += (data['history']['3600'][-1]['avg']) count += 1 if count == 0: self.add_message('CPU', 'WARNING', 'Average CPU load is not collected yet') else: cpu_avg = cpu_percent / float(count) self.add_message(**get_message('cpu', cpu_avg)) def get_message(type_, percent): message = { 'id': type_.upper(), 'status': 'OK', 'text': r'Average %s load during last hour was: %.2f%%' % (type_.upper(), percent), } if percent > 95: message['status'] = 'ERROR' message['text'] = r'Average %s load during last hour was too high' % (type_.upper()) elif percent > 80: message['status'] = 'WARNING' message['text'] = r'Average %s load during last hour was too high' % (type_.upper()) return message
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/healthchecks/cpu_mem_core.py
cpu_mem_core.py
import signal import time import requests from js9 import j class Grafana: def __init__(self, container, ip, port, url): self.container = container self.ip = ip self.port = port self.url = url self.client = j.clients.grafana.get(url='http://%s:%d' % ( ip, port), username='admin', password='admin') def apply_config(self): f = self.container.client.filesystem.open('/opt/grafana/conf/defaults.ini') try: template = self.container.client.filesystem.read(f) finally: self.container.client.filesystem.close(f) template = template.replace(b'3000', str(self.port).encode()) if self.url: template = template.replace(b'root_url = %(protocol)s://%(domain)s:%(http_port)s/', b'root_url = %s' % self.url.encode()) self.container.client.filesystem.mkdir('/etc/grafana/') self.container.upload_content('/etc/grafana/grafana.ini', template) def is_running(self): for process in self.container.client.process.list(): if 'grafana-server' in process['cmdline']: return True, process['pid'] return False, None def stop(self, timeout=30): is_running, pid = self.is_running() if not is_running: return self.container.client.process.kill(pid, signal.SIGTERM) start = time.time() end = start + timeout is_running, _ = self.is_running() while is_running and time.time() < end: time.sleep(1) is_running, _ = self.is_running() if is_running: raise RuntimeError('Failed to stop grafana.') if self.container.node.client.nft.rule_exists(self.port): self.container.node.client.nft.drop_port(self.port) def start(self, timeout=30): is_running, _ = self.is_running() if is_running: return self.apply_config() if not self.container.node.client.nft.rule_exists(self.port): self.container.node.client.nft.open_port(self.port) self.container.client.system( 'grafana-server -config /etc/grafana/grafana.ini -homepath /opt/grafana') time.sleep(1) start = time.time() end = start + timeout is_running, _ = self.is_running() while not is_running and time.time() < end: time.sleep(1) is_running, _ = self.is_running() if not is_running: if self.container.node.client.nft.rule_exists(self.port): self.container.node.client.nft.drop_port(self.port) raise RuntimeError('Failed to start grafana.') def add_data_source(self, database, name, ip, port, count): data = { 'type': 'influxdb', 'access': 'proxy', 'database': database, 'name': name, 'url': 'http://%s:%u' % (ip, port), 'user': 'admin', 'password': 'passwd', 'default': True, } now = time.time() while time.time() - now < 10: try: self.client.addDataSource(data) if len(self.client.listDataSources()) == count + 1: continue break except requests.exceptions.ConnectionError: time.sleep(1) pass
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/grafana/grafana.py
grafana.py
import signal import time from zeroos.orchestrator.sal import templates from js9 import j class InfluxDB: def __init__(self, container, ip, port): self.container = container self.ip = ip self.port = port def apply_config(self): influx_conf = templates.render('influxdb.conf', ip=self.ip, port=self.port) self.container.upload_content('/etc/influxdb/influxdb.conf', influx_conf) def is_running(self): for process in self.container.client.process.list(): if 'influxd' in process['cmdline']: try: self.list_databases() except: return False, process['pid'] else: return True, process['pid'] return False, None def stop(self, timeout=30): is_running, pid = self.is_running() if not is_running: return self.container.client.process.kill(pid, signal.SIGTERM) start = time.time() end = start + timeout is_running, _ = self.is_running() while is_running and time.time() < end: time.sleep(1) is_running, _ = self.is_running() if is_running: raise RuntimeError('Failed to stop influxd.') if self.container.node.client.nft.rule_exists(self.port): self.container.node.client.nft.drop_port(self.port) def start(self, timeout=30): is_running, _ = self.is_running() if is_running: return self.apply_config() if not self.container.node.client.nft.rule_exists(self.port): self.container.node.client.nft.open_port(self.port) self.container.client.system('influxd') time.sleep(1) start = time.time() end = start + timeout is_running, _ = self.is_running() while not is_running and time.time() < end: time.sleep(1) is_running, _ = self.is_running() if not is_running: if self.container.node.client.nft.rule_exists(self.port): self.container.node.client.nft.drop_port(self.port) raise RuntimeError('Failed to start influxd.') def list_databases(self): client = j.clients.influxdb.get(self.ip, port=self.port) return client.get_list_database() def create_databases(self, databases): client = j.clients.influxdb.get(self.ip, port=self.port) for database in databases: client.create_database(database) def drop_databases(self, databases): client = j.clients.influxdb.get(self.ip, port=self.port) for database in databases: client.drop_database(database)
0-orchestrator
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/influxdb/influxdb.py
influxdb.py
import os import sys import math import json import pandas as pd import tensorflow as tf from .settings import VALID_SPLIT_NAME, DEFAUT_SAVE_FILE_PATTERN from .settings import LABELS_FILENAME, SUMMARY_FILE_PATTERN class ImageReader(object): """Helper class that provides TensorFlow image coding utilities.""" # TODO: need save the label file. and information that tell size of each split # def __init__(self): """Create a Reader for reading image information.""" # Initializes function that decodes RGB JPEG data. self._decode_jpeg_data = tf.placeholder(dtype=tf.string) self._decode_jpeg = tf.image.decode_image(self._decode_jpeg_data, channels=3) def read_image_dims(self, sess, image_data): """Read dimension of image.""" image = self.decode_image(sess, image_data) return image.shape[0], image.shape[1] def decode_image(self, sess, image_data): """Decode jpeg image.""" # TODO: only support jpg format. add other formate support. image = sess.run(self._decode_jpeg, feed_dict={self._decode_jpeg_data: image_data}) assert len(image.shape) == 3 assert image.shape[2] == 3 return image class Image2TFRecords(object): """ Convert images and into tfrecords. Parameters: --------------------- image_path: path where you put your images image2class_file: csv file which contains classname for every image file Format: filename, class 1.jpg , cat 2.jpg , dog .. , .. you must provide a valid header for csv file. Headers will be used in tfrecord to represent dataset-specific information. dataset_name: the resuliting tfrecord file will have following name: dataset_name_splitname_xxxxx_of_xxxxx.tfrecords class2id_file: csv file which contains classid for every class in image2class_file Format: classname, class_id 1.jpg , cat 2.jpg , dog .. , .. you must provide a valid header for csv file. Headers will be used in tfrecord to represent dataset-specific information. val_size: percentage for validation dataset. if you don't want split your data into train/validation/test. set it to 0 test_size: same as val_size num_shards: The number of shards per dataset split. """ def __init__(self, image_path, image2class_file, class2id_file=None, dataset_name='', val_size=0, test_size=0, num_shards=5): """ Construtor of Image2TFRecords. only image_path and image2class_file is mandantory """ # TODO: add path validation. check valid image exists # current support image formate: bmp, gif, jpeg,_png # Parameter validation if (val_size < 0 or val_size > 1) or\ ((test_size < 0 or test_size > 1)) or\ (val_size+test_size > 1): raise RuntimeError("val_size and test_size must between 0 and 1 and Their \ sum can't exceed 1") self.image_path = image_path # TODO: check map file format self.image2class_file = image2class_file self.class2id_file = class2id_file self.dataset_name = dataset_name self.val_size = val_size self.test_size = test_size self.num_shards = num_shards self.dataset_summary = {} # create class image_path self._create_class_map() # after create class map. we can get total number of samples self.total_number = len(self.image2class) self.dataset_summary["total_number"] = self.total_number def _save_summary_file(self, output_dir): summary_file = os.path.join( output_dir, SUMMARY_FILE_PATTERN % (self.dataset_name,)) with open(summary_file, 'w') as fd: json.dump(self.dataset_summary, fd) print("write summary file done") def _write_class2id_file(self, output_dir): self.class2id.to_csv( os.path.join(output_dir, LABELS_FILENAME), index=False) print("write label file done") def _create_class_map(self): # 1. first read image2class_file self.image2class = pd.read_csv(self.image2class_file) # require filename at 1st column and class at 2nd will simplify the parameters # but may require use do more pre-process. which is better? self.filename_header = self.image2class.columns[0] self.class_header = self.image2class.columns[1] # 1.1 process image2class. strip padding space def strip_space(data): return pd.Series([d.strip() for d in data]) self.image2class = self.image2class.apply(strip_space, axis=0) # 2. then check if there is: class 2 class_id file. # yes: read it # no: create one if self.class2id_file: self.class2id = pd.read_csv(self.class2id_file) self.class_id_header = self.class2id.columns[1] else: self.class_id_header = self.class_header+"_id" self.class2id = pd.DataFrame(columns=[self.class_header, self.class_id_header]) id_count = 0 for col in self.image2class[self.class_header]: if not (col in self.class2id[self.class_header].tolist()): self.class2id = pd.concat( [self.class2id, pd.DataFrame({self.class_header: [col], self.class_id_header: [id_count]}) ]) id_count += 1 self.class2id = self.class2id.reset_index(drop=True) # save header information to disk self.dataset_summary["filename_header"] = self.filename_header self.dataset_summary["class_header"] = self.class_header self.dataset_summary["class_id_header"] = self.class_id_header return self.image2class, self.class2id def _get_dataset_filename(self, split_name, shard_id, output_dir): output_filename = DEFAUT_SAVE_FILE_PATTERN % ( self.dataset_name, split_name, shard_id+1, self.num_shards) if output_dir: return os.path.join(output_dir, output_filename) else: return output_filename def _int64_feature(self, values): """Return a TF-Feature of int64s. Args: values: A scalar or list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) def _bytes_feature(self, values): """Return a TF-Feature of bytes. Args: values: A string. Returns: A TF-Feature. """ return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values])) def _float_feature(self, values): """Return a TF-Feature of floats. Args: values: A scalar of list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(float_list=tf.train.FloatList(value=values)) def _image_to_tfexample(self, image_data, image_format, height, width, class_id, filename): return tf.train.Example(features=tf.train.Features(feature={ 'image/encoded': self._bytes_feature(image_data), 'image/format': self._bytes_feature(image_format), 'image/class/label': self._int64_feature(class_id), 'image/height': self._int64_feature(height), 'image/width': self._int64_feature(width), 'image/filename': self._bytes_feature(filename) })) def _convert_dataset(self, split_name, image_index, output_dir): """Convert the images of give index into . Args: split_name: The name of the dataset, either 'train', 'validation' or "test" image_index: The index used to select image from image2class dataframe. """ assert split_name in VALID_SPLIT_NAME assert len(image_index) > 0 num_per_shard = int(math.ceil(len(image_index) / float(self.num_shards))) with tf.Graph().as_default(): image_reader = ImageReader() with tf.Session('') as sess: # TODO: shards have problem, if total number of dataset is too small. for shard_id in range(self.num_shards): output_filename = self._get_dataset_filename(split_name, shard_id, output_dir) with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer: start_ndx = shard_id * num_per_shard end_ndx = min((shard_id+1) * num_per_shard, len(image_index)) for i in range(start_ndx, end_ndx): sys.stdout.write('\r>> Converting image %d/%d shard %d' % ( i+1, len(image_index), shard_id)) sys.stdout.flush() # Read the filename: image_filename = self.image2class.loc[image_index[i], self.filename_header] image_data = tf.gfile.FastGFile( os.path.join(self.image_path, image_filename), 'rb').read() height, width = image_reader.read_image_dims(sess, image_data) class_name = self.image2class.loc[image_index[i], self.class_header] class_id = self.class2id[ self.class2id[self.class_header] == class_name][self.class_id_header] # at this step, class_id is a Series with only 1 element. convert it to int class_id = int(class_id) image_format = os.path.splitext(image_filename)[1][1:] example = self._image_to_tfexample( image_data, image_format.encode('utf-8'), height, width, class_id, image_filename.encode('utf-8')) tfrecord_writer.write(example.SerializeToString()) sys.stdout.write('\n') sys.stdout.flush() def create_tfrecords(self, output_dir): """ Create tfrecord. Parameters: output_dir: Where to put the tfrecords file. """ if not os.path.isdir(output_dir): os.makedirs(output_dir) train_index = [] val_index = [] test_index = [] def draw_sample(df_class): # split data into 3 split # 1. calculate number of each split total_number = len(df_class.index) test_number = math.floor(total_number*self.test_size) val_number = math.floor(total_number*self.val_size) train_number = total_number - test_number - val_number # because I use floor when I calculate test and val size. # There is a chance that train_number is 1 but # self.test_size + self.val_number == 1 # for example: # total: 99, eval=0.1, test=0.9 # 9.9->9 89.1->89 # in this case. add this train_number to test set if train_number == 1: train_number = 0 test_number += 1 if val_number > 0: t_val_index = df_class.sample(val_number).index df_class = df_class.drop(t_val_index) val_index.extend(t_val_index) if test_number > 0: t_test_index = df_class.sample(test_number).index df_class = df_class.drop(t_test_index) test_index.extend(t_test_index) if train_number: t_train_index = df_class.index train_index.extend(t_train_index) # self.image2class.groupby(self.class_header).apply(draw_sample) for name, group in self.image2class.groupby(self.class_header): draw_sample(group) self.train_number = len(train_index) self.val_number = len(val_index) self.test_number = len(test_index) assert((self.train_number + self.val_number + self.test_number) == self.total_number) # def _convert_dataset(self, split_name, image_index, output_dir) if self.train_number: self._convert_dataset("train", train_index, output_dir) if self.val_number: self._convert_dataset("validation", val_index, output_dir) if self.test_number: self._convert_dataset("test", test_index, output_dir) self.dataset_summary["train_number"] = self.train_number self.dataset_summary["val_number"] = self.val_number self.dataset_summary["test_number"] = self.test_number # write summary file self._save_summary_file(output_dir) # write lable file self._write_class2id_file(output_dir)
0.0.1
/0.0.1-0.0.1.tar.gz/0.0.1-0.0.1/image2tfrecords/image2tfrecords.py
image2tfrecords.py
import json import os import pandas as pd import tensorflow as tf from tensorflow.contrib import slim # TODO: try tf.data API. because slim is not an official API. from .settings import (DEFAULT_READ_FILE_PATTERN, LABELS_FILENAME, SUMMARY_FILE_PATTERN, VALID_SPLIT_NAME) _ITEMS_TO_DESCRIPTIONS = { 'image': 'A color image of varying size.', 'label': 'A single integer represent class of sample', } class ImageDataSet(object): """ Read Data From tfrecords. Usage: """ def __init__(self, tfrecords_dir, dataset_name=''): """Create a ImageDataSet.""" self.tfrecords_dir = tfrecords_dir self.dataset_name = dataset_name # read summary information try: summary_file = os.path.join( tfrecords_dir, SUMMARY_FILE_PATTERN % (self.dataset_name)) with open(summary_file) as fd: self.dataset_summary = json.load(fd) except Exception as ex: raise RuntimeError("summary file don't exsits: %s" % (summary_file,)) # read label file try: label_file = os.path.join(self.tfrecords_dir, LABELS_FILENAME) self.labels_df = pd.read_csv(label_file) self.labels_to_class_names = {} for i in self.labels_df.index: self.labels_to_class_names[ self.labels_df.loc[i, self.dataset_summary["class_id_header"]]] =\ self.labels_df.loc[i, self.dataset_summary["class_header"]] except Exception as ex: raise RuntimeError("label file don't exsits: %s" % (label_file,)) # def _has_label_file(self): # return os.path.isfile(os.path.join(self.tfrecords_dir, LABELS_FILENAME)) # # def _read_label_file(self): # labels_df = pd.read_csv(os.path.join(self.tfrecords_dir, LABELS_FILENAME)) # labels_to_class_names = {} # for i in labels_df.index: # labels_to_class_names[labels_df.loc[i, self.dataset_summary["class_id_header"]]] =\ # labels_df.loc[i, self.dataset_summary["class_header"]] # return labels_to_class_names def get_split(self, split_name, file_pattern=None): """ Get a DataSet from tfrecords file. Parameters: split_name: name of split: train, validation, test file_pattern: pattern to find tfrecord files from directory Returns: A DataSet namedtuple """ if split_name not in VALID_SPLIT_NAME: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = DEFAULT_READ_FILE_PATTERN file_pattern = os.path.join( self.tfrecords_dir, file_pattern % (self.dataset_name, split_name)) reader = tf.TFRecordReader keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='png'), 'image/class/label': tf.FixedLenFeature( [], tf.int64, default_value=tf.zeros([], dtype=tf.int64)), 'image/filename': tf.FixedLenFeature((), tf.string, default_value=''), } items_to_handlers = { 'image': slim.tfexample_decoder.Image(), 'label': slim.tfexample_decoder.Tensor('image/class/label'), 'filename': slim.tfexample_decoder.Tensor('image/filename'), } decoder = slim.tfexample_decoder.TFExampleDecoder( keys_to_features, items_to_handlers) # labels_to_names = None # if self._has_label_file(): # labels_to_names = self._read_label_file() sample_name_dict = {"train": "train_number", "validation": "val_number", "test": "test_number"} return slim.dataset.Dataset( data_sources=file_pattern, reader=reader, decoder=decoder, num_samples=self.dataset_summary[sample_name_dict[split_name]], items_to_descriptions=_ITEMS_TO_DESCRIPTIONS, num_classes=len(self.labels_to_class_names.keys()), labels_to_names=self.labels_to_class_names)
0.0.1
/0.0.1-0.0.1.tar.gz/0.0.1-0.0.1/image2tfrecords/imagedataset.py
imagedataset.py
📦 setup.py (for humans) ======================= This repo exists to provide [an example setup.py] file, that can be used to bootstrap your next Python project. It includes some advanced patterns and best practices for `setup.py`, as well as some commented–out nice–to–haves. For example, this `setup.py` provides a `$ python setup.py upload` command, which creates a *universal wheel* (and *sdist*) and uploads your package to [PyPi] using [Twine], without the need for an annoying `setup.cfg` file. It also creates/uploads a new git tag, automatically. In short, `setup.py` files can be daunting to approach, when first starting out — even Guido has been heard saying, "everyone cargo cults thems". It's true — so, I want this repo to be the best place to copy–paste from :) [Check out the example!][an example setup.py] Installation ----- ```bash cd your_project # Download the setup.py file: # download with wget wget https://raw.githubusercontent.com/navdeep-G/setup.py/master/setup.py -O setup.py # download with curl curl -O https://raw.githubusercontent.com/navdeep-G/setup.py/master/setup.py ``` To Do ----- - Tests via `$ setup.py test` (if it's concise). Pull requests are encouraged! More Resources -------------- - [What is setup.py?] on Stack Overflow - [Official Python Packaging User Guide](https://packaging.python.org) - [The Hitchhiker's Guide to Packaging] - [Cookiecutter template for a Python package] License ------- This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. [an example setup.py]: https://github.com/navdeep-G/setup.py/blob/master/setup.py [PyPi]: https://docs.python.org/3/distutils/packageindex.html [Twine]: https://pypi.python.org/pypi/twine [image]: https://farm1.staticflickr.com/628/33173824932_58add34581_k_d.jpg [What is setup.py?]: https://stackoverflow.com/questions/1471994/what-is-setup-py [The Hitchhiker's Guide to Packaging]: https://the-hitchhikers-guide-to-packaging.readthedocs.io/en/latest/creation.html [Cookiecutter template for a Python package]: https://github.com/audreyr/cookiecutter-pypackage
0.618
/0.618-0.1.0.tar.gz/0.618-0.1.0/README.md
README.md
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Gaussian(Distribution): """ Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ def __init__(self, mu=0, sigma=1): Distribution.__init__(self, mu, sigma) def calculate_mean(self): """Function to calculate the mean of the data set. Args: None Returns: float: mean of the data set """ avg = 1.0 * sum(self.data) / len(self.data) self.mean = avg return self.mean def calculate_stdev(self, sample=True): """Function to calculate the standard deviation of the data set. Args: sample (bool): whether the data represents a sample or population Returns: float: standard deviation of the data set """ if sample: n = len(self.data) - 1 else: n = len(self.data) mean = self.calculate_mean() sigma = 0 for d in self.data: sigma += (d - mean) ** 2 sigma = math.sqrt(sigma / n) self.stdev = sigma return self.stdev def plot_histogram(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.hist(self.data) plt.title('Histogram of Data') plt.xlabel('data') plt.ylabel('count') def pdf(self, x): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2) def plot_histogram_pdf(self, n_spaces = 50): """Function to plot the normalized histogram of the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ mu = self.mean sigma = self.stdev min_range = min(self.data) max_range = max(self.data) # calculates the interval between x values interval = 1.0 * (max_range - min_range) / n_spaces x = [] y = [] # calculate the x values to visualize for i in range(n_spaces): tmp = min_range + interval*i x.append(tmp) y.append(self.pdf(tmp)) # make the plots fig, axes = plt.subplots(2,sharex=True) fig.subplots_adjust(hspace=.5) axes[0].hist(self.data, density=True) axes[0].set_title('Normed Histogram of Data') axes[0].set_ylabel('Density') axes[1].plot(x, y) axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') axes[0].set_ylabel('Density') plt.show() return x, y def __add__(self, other): """Function to add together two Gaussian distributions Args: other (Gaussian): Gaussian instance Returns: Gaussian: Gaussian distribution """ result = Gaussian() result.mean = self.mean + other.mean result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2) return result def __repr__(self): """Function to output the characteristics of the Gaussian instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}".format(self.mean, self.stdev)
01-distributions
/01_distributions-0.1.tar.gz/01_distributions-0.1/01_distributions/Gaussiandistribution.py
Gaussiandistribution.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Binomial(Distribution): """ Binomial distribution class for calculating and visualizing a Binomial distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats to be extracted from the data file p (float) representing the probability of an event occurring n (int) number of trials TODO: Fill out all functions below """ def __init__(self, prob=.5, size=20): self.n = size self.p = prob Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev()) def calculate_mean(self): """Function to calculate the mean from p and n Args: None Returns: float: mean of the data set """ self.mean = self.p * self.n return self.mean def calculate_stdev(self): """Function to calculate the standard deviation from p and n. Args: None Returns: float: standard deviation of the data set """ self.stdev = math.sqrt(self.n * self.p * (1 - self.p)) return self.stdev def replace_stats_with_data(self): """Function to calculate p and n from the data set Args: None Returns: float: the p value float: the n value """ self.n = len(self.data) self.p = 1.0 * sum(self.data) / len(self.data) self.mean = self.calculate_mean() self.stdev = self.calculate_stdev() def plot_bar(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n]) plt.title('Bar Chart of Data') plt.xlabel('outcome') plt.ylabel('count') def pdf(self, k): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k))) b = (self.p ** k) * (1 - self.p) ** (self.n - k) return a * b def plot_bar_pdf(self): """Function to plot the pdf of the binomial distribution Args: None Returns: list: x values for the pdf plot list: y values for the pdf plot """ x = [] y = [] # calculate the x values to visualize for i in range(self.n + 1): x.append(i) y.append(self.pdf(i)) # make the plots plt.bar(x, y) plt.title('Distribution of Outcomes') plt.ylabel('Probability') plt.xlabel('Outcome') plt.show() return x, y def __add__(self, other): """Function to add together two Binomial distributions with equal p Args: other (Binomial): Binomial instance Returns: Binomial: Binomial distribution """ try: assert self.p == other.p, 'p values are not equal' except AssertionError as error: raise result = Binomial() result.n = self.n + other.n result.p = self.p result.calculate_mean() result.calculate_stdev() return result def __repr__(self): """Function to output the characteristics of the Binomial instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}, p {}, n {}".\ format(self.mean, self.stdev, self.p, self.n)
01-distributions
/01_distributions-0.1.tar.gz/01_distributions-0.1/01_distributions/Binomialdistribution.py
Binomialdistribution.py
======== Overview ======== .. start-badges .. list-table:: :stub-columns: 1 * - docs - |docs| * - tests - | |travis| |appveyor| | * - package - | |version| |wheel| |supported-versions| |supported-implementations| | |commits-since| .. |docs| image:: https://readthedocs.org/projects/01d61084-d29e-11e9-96d1-7c5cf84ffe8e/badge/?style=flat :target: https://readthedocs.org/projects/01d61084-d29e-11e9-96d1-7c5cf84ffe8e :alt: Documentation Status .. |travis| image:: https://travis-ci.org/python-retool/01d61084-d29e-11e9-96d1-7c5cf84ffe8e.svg?branch=master :alt: Travis-CI Build Status :target: https://travis-ci.org/python-retool/01d61084-d29e-11e9-96d1-7c5cf84ffe8e .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/github/python-retool/01d61084-d29e-11e9-96d1-7c5cf84ffe8e?branch=master&svg=true :alt: AppVeyor Build Status :target: https://ci.appveyor.com/project/python-retool/01d61084-d29e-11e9-96d1-7c5cf84ffe8e .. |version| image:: https://img.shields.io/pypi/v/01d61084-d29e-11e9-96d1-7c5cf84ffe8e.svg :alt: PyPI Package latest release :target: https://pypi.org/pypi/01d61084-d29e-11e9-96d1-7c5cf84ffe8e .. |commits-since| image:: https://img.shields.io/github/commits-since/python-retool/01d61084-d29e-11e9-96d1-7c5cf84ffe8e/v0.1.0.svg :alt: Commits since latest release :target: https://github.com/python-retool/01d61084-d29e-11e9-96d1-7c5cf84ffe8e/compare/v0.1.0...master .. |wheel| image:: https://img.shields.io/pypi/wheel/01d61084-d29e-11e9-96d1-7c5cf84ffe8e.svg :alt: PyPI Wheel :target: https://pypi.org/pypi/01d61084-d29e-11e9-96d1-7c5cf84ffe8e .. |supported-versions| image:: https://img.shields.io/pypi/pyversions/01d61084-d29e-11e9-96d1-7c5cf84ffe8e.svg :alt: Supported versions :target: https://pypi.org/pypi/01d61084-d29e-11e9-96d1-7c5cf84ffe8e .. |supported-implementations| image:: https://img.shields.io/pypi/implementation/01d61084-d29e-11e9-96d1-7c5cf84ffe8e.svg :alt: Supported implementations :target: https://pypi.org/pypi/01d61084-d29e-11e9-96d1-7c5cf84ffe8e .. end-badges An example package. Generated with cookiecutter-pylibrary. * Free software: BSD 2-Clause License Installation ============ :: pip install 01d61084-d29e-11e9-96d1-7c5cf84ffe8e Documentation ============= https://01d61084-d29e-11e9-96d1-7c5cf84ffe8e.readthedocs.io/ Development =========== To run the all tests run:: tox Note, to combine the coverage data from all the tox environments run: .. list-table:: :widths: 10 90 :stub-columns: 1 - - Windows - :: set PYTEST_ADDOPTS=--cov-append tox - - Other - :: PYTEST_ADDOPTS=--cov-append tox
01d61084-d29e-11e9-96d1-7c5cf84ffe8e
/01d61084-d29e-11e9-96d1-7c5cf84ffe8e-0.1.0.tar.gz/01d61084-d29e-11e9-96d1-7c5cf84ffe8e-0.1.0/README.rst
README.rst
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
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
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
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
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
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
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
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
ハロー・ゼロ ============ 使い方 ------ `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
# 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
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
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
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
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
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
# 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
# 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
# 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
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
# 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
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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
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
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
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
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
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
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
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
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
# 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
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
# Web3.py [![Join the chat at https://gitter.im/ethereum/web3.py](https://badges.gitter.im/ethereum/web3.py.svg)](https://gitter.im/ethereum/web3.py?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://circleci.com/gh/ethereum/web3.py.svg?style=shield)](https://circleci.com/gh/ethereum/web3.py) A Python implementation of [web3.js](https://github.com/ethereum/web3.js) * Python 3.6+ support Read more in the [documentation on ReadTheDocs](http://web3py.readthedocs.io/). [View the change log on Github](docs/releases.rst). ## Developer Setup ```sh git clone git@github.com:ethereum/web3.py.git cd web3.py ``` Please see OS-specific instructions for: - [Linux](docs/README-linux.md#Developer-Setup) - [Mac](docs/README-osx.md#Developer-Setup) - [Windows](docs/README-windows.md#Developer-Setup) - [FreeBSD](docs/README-freebsd.md#Developer-Setup) Then run these install commands: ```sh virtualenv venv . venv/bin/activate pip install -e .[dev] ``` For different environments, you can set up multiple `virtualenv`. For example, if you want to create a `venvdocs`, then you do the following: ```sh virtualenv venvdocs . venvdocs/bin/activate pip install -e .[docs] pip install -e . ``` ## Using Docker If you would like to develop and test inside a Docker environment, use the *sandbox* container provided in the **docker-compose.yml** file. To start up the test environment, run: ``` docker-compose up -d ``` This will build a Docker container set up with an environment to run the Python test code. **Note: This container does not have `go-ethereum` installed, so you cannot run the go-ethereum test suite.** To run the Python tests from your local machine: ``` docker-compose exec sandbox bash -c 'pytest -n 4 -f -k "not goethereum"' ``` You can run arbitrary commands inside the Docker container by using the `bash -c` prefix. ``` docker-compose exec sandbox bash -c '' ``` Or, if you would like to just open a session to the container, run: ``` docker-compose exec sandbox bash ``` ### Testing Setup During development, you might like to have tests run on every file save. Show flake8 errors on file change: ```sh # Test flake8 when-changed -v -s -r -1 web3/ tests/ ens/ -c "clear; flake8 web3 tests ens && echo 'flake8 success' || echo 'error'" ``` You can use `pytest-watch`, running one for every Python environment: ```sh pip install pytest-watch cd venv ptw --onfail "notify-send -t 5000 'Test failure ⚠⚠⚠⚠⚠' 'python 3 test on web3.py failed'" ../tests ../web3 ``` Or, you can run multi-process tests in one command, but without color: ```sh # in the project root: pytest --numprocesses=4 --looponfail --maxfail=1 # the same thing, succinctly: pytest -n 4 -f --maxfail=1 ``` #### How to Execute the Tests? 1. [Setup your development environment](https://github.com/ethereum/web3.py/#developer-setup). 2. Execute `tox` for the tests There are multiple [components](https://github.com/ethereum/web3.py/blob/master/.travis.yml#L53) of the tests. You can run test to against specific component. For example: ```sh # Run Tests for the Core component (for Python 3.5): tox -e py35-core # Run Tests for the Core component (for Python 3.6): tox -e py36-core ``` If for some reason it is not working, add `--recreate` params. `tox` is good for testing against the full set of build targets. But if you want to run the tests individually, `py.test` is better for development workflow. For example, to run only the tests in one file: ```sh py.test tests/core/gas-strategies/test_time_based_gas_price_strategy.py ``` ### Release setup For Debian-like systems: ``` apt install pandoc ``` To release a new version: ```sh make release bump=$$VERSION_PART_TO_BUMP$$ ``` #### How to bumpversion The version format for this repo is `{major}.{minor}.{patch}` for stable, and `{major}.{minor}.{patch}-{stage}.{devnum}` for unstable (`stage` can be alpha or beta). To issue the next version in line, specify which part to bump, like `make release bump=minor` or `make release bump=devnum`. If you are in a beta version, `make release bump=stage` will switch to a stable. To issue an unstable version when the current version is stable, specify the new version explicitly, like `make release bump="--new-version 4.0.0-alpha.1 devnum"`
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/README.md
README.md
import json registrar_abi = json.loads('[{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"releaseDeed","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"getAllowedTime","outputs":[{"name":"timestamp","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"unhashedName","type":"string"}],"name":"invalidateName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"hash","type":"bytes32"},{"name":"owner","type":"address"},{"name":"value","type":"uint256"},{"name":"salt","type":"bytes32"}],"name":"shaBid","outputs":[{"name":"sealedBid","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bidder","type":"address"},{"name":"seal","type":"bytes32"}],"name":"cancelBid","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"entries","outputs":[{"name":"","type":"uint8"},{"name":"","type":"address"},{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"ens","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"_value","type":"uint256"},{"name":"_salt","type":"bytes32"}],"name":"unsealBid","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"transferRegistrars","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"bytes32"}],"name":"sealedBids","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"state","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"newOwner","type":"address"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"_timestamp","type":"uint256"}],"name":"isAllowed","outputs":[{"name":"allowed","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"finalizeAuction","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"registryStarted","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"launchLength","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"sealedBid","type":"bytes32"}],"name":"newBid","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"labels","type":"bytes32[]"}],"name":"eraseNode","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_hashes","type":"bytes32[]"}],"name":"startAuctions","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"hash","type":"bytes32"},{"name":"deed","type":"address"},{"name":"registrationDate","type":"uint256"}],"name":"acceptRegistrarTransfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"startAuction","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"rootNode","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"hashes","type":"bytes32[]"},{"name":"sealedBid","type":"bytes32"}],"name":"startAuctionsAndBid","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"_ens","type":"address"},{"name":"_rootNode","type":"bytes32"},{"name":"_startDate","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"AuctionStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"bidder","type":"address"},{"indexed":false,"name":"deposit","type":"uint256"}],"name":"NewBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"status","type":"uint8"}],"name":"BidRevealed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"HashRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":false,"name":"value","type":"uint256"}],"name":"HashReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"name","type":"string"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"HashInvalidated","type":"event"}]') registrar_bytecode = "6060604052341561000f57600080fd5b60405160608061275783398101604052808051919060200180519190602001805160008054600160a060020a031916600160a060020a0387161781556001859055909250821190506100615742610063565b805b6004555050506126df806100786000396000f300606060405236156101175763ffffffff60e060020a6000350416630230a07c811461011c57806313c89a8f1461013457806315f733311461015c57806322ec1244146101ad5780632525f5c1146101d5578063267b6922146101f75780633f15457f1461025f57806347872b421461028e5780635ddae283146102aa5780635e431709146102c057806361d585da146102e257806379ce9fac1461031c578063935033371461033e578063983b94fb1461036b5780639c67f06f14610381578063ae1a0b0c14610394578063ce92dced146103c0578063de10f04b146103cb578063e27fe50f1461041a578063ea9e107a14610469578063ede8acdb1461048e578063faff50a8146104a4578063febefd61146104b7575b600080fd5b341561012757600080fd5b6101326004356104fd565b005b341561013f57600080fd5b61014a60043561072a565b60405190815260200160405180910390f35b341561016757600080fd5b61013260046024813581810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284375094965061074e95505050505050565b34156101b857600080fd5b61014a600435600160a060020a0360243516604435606435610a7a565b34156101e057600080fd5b610132600160a060020a0360043516602435610ac5565b341561020257600080fd5b61020d600435610c8c565b6040518086600581111561021d57fe5b60ff16815260200185600160a060020a0316600160a060020a031681526020018481526020018381526020018281526020019550505050505060405180910390f35b341561026a57600080fd5b610272610cd8565b604051600160a060020a03909116815260200160405180910390f35b341561029957600080fd5b610132600435602435604435610ce7565b34156102b557600080fd5b610132600435611254565b34156102cb57600080fd5b610272600160a060020a03600435166024356114b4565b34156102ed57600080fd5b6102f86004356114da565b6040518082600581111561030857fe5b60ff16815260200191505060405180910390f35b341561032757600080fd5b610132600435600160a060020a0360243516611550565b341561034957600080fd5b61035760043560243561169b565b604051901515815260200160405180910390f35b341561037657600080fd5b6101326004356116b1565b341561038c57600080fd5b61014a611919565b341561039f57600080fd5b6103a761191f565b60405163ffffffff909116815260200160405180910390f35b610132600435611926565b34156103d657600080fd5b6101326004602481358181019083013580602081810201604051908101604052809392919081815260200183836020028082843750949650611a1a95505050505050565b341561042557600080fd5b6101326004602481358181019083013580602081810201604051908101604052809392919081815260200183836020028082843750949650611a7595505050505050565b341561047457600080fd5b610132600435600160a060020a0360243516604435611aab565b341561049957600080fd5b610132600435611ab0565b34156104af57600080fd5b61014a611bfc565b61013260046024813581810190830135806020818102016040519081016040528093929190818152602001838360200280828437509496505093359350611c0292505050565b60008082600261050c826114da565b600581111561051757fe5b1415806105a3575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561057257600080fd5b6102c65a03f1151561058357600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b156105ad57600080fd5b600084815260026020526040902080546001820154919450600160a060020a031692506301e13380014210801561065f575060008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561063957600080fd5b6102c65a03f1151561064a57600080fd5b50505060405180519050600160a060020a0316145b1561066957600080fd5b60006002840181905560038401558254600160a060020a031916835561068e84611c14565b81600160a060020a031663bbe427716103e860405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156106d657600080fd5b6102c65a03f115156106e757600080fd5b505050600283015484907f292b79b9246fa2c8e77d3fe195b251f9cb839d7d038e667c069ee7708c631e169060405190815260200160405180910390a250505050565b6004547001000000000000000000000000000000006249d400818404020401919050565b600080826040518082805190602001908083835b602083106107815780518252601f199092019160209182019101610762565b6001836020036101000a03801982511681845116179092525050509190910192506040915050519081900390206002806107ba836114da565b60058111156107c557fe5b146107cf57600080fd5b60066107da86611e12565b11156107e557600080fd5b846040518082805190602001908083835b602083106108155780518252601f1990920191602091820191016107f6565b6001836020036101000a03801982511681845116179092525050509190910192506040915050519081900390206000818152600260205260409020909450925061085e84611c14565b8254600160a060020a0316156109b5576108838360020154662386f26fc10000611ec3565b60028085018290558454600160a060020a03169163b0c80972919004600060405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b15156108de57600080fd5b6102c65a03f115156108ef57600080fd5b50508354600160a060020a031690506313af40353360405160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b151561094257600080fd5b6102c65a03f1151561095357600080fd5b50508354600160a060020a0316905063bbe427716103e860405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156109a057600080fd5b6102c65a03f115156109b157600080fd5b5050505b846040518082805190602001908083835b602083106109e55780518252601f1990920191602091820191016109c6565b6001836020036101000a0380198251168184511617909252505050919091019250604091505051809103902084600019167f1f9c649fe47e58bb60f4e52f0d90e4c47a526c9f90c5113df842c025970b66ad8560020154866001015460405191825260208201526040908101905180910390a3505060006002820181905560038201558054600160a060020a03191690555050565b600084848484604051938452600160a060020a03929092166c010000000000000000000000000260208401526034830152605482015260740160405180910390209050949350505050565b600160a060020a03808316600090815260036020908152604080832085845290915290205416801580610b61575062069780600160a060020a0382166305b344106000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610b3d57600080fd5b6102c65a03f11515610b4e57600080fd5b5050506040518051905001621275000142105b15610b6b57600080fd5b80600160a060020a03166313af40353360405160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b1515610bb957600080fd5b6102c65a03f11515610bca57600080fd5b50505080600160a060020a031663bbe42771600560405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610c1457600080fd5b6102c65a03f11515610c2557600080fd5b505050600160a060020a03831660008181526003602090815260408083208684529091528082208054600160a060020a03191690558491600080516020612694833981519152916005905191825260ff1660208201526040908101905180910390a3505050565b60008181526002602052604081208190819081908190610cab876114da565b815460018301546002840154600390940154929a600160a060020a03909216995097509195509350915050565b600054600160a060020a031681565b600080600080600080610cfc89338a8a610a7a565b600160a060020a033381166000908152600360209081526040808320858452909152902054919750169450841515610d3357600080fd5b600160a060020a0333811660009081526003602090815260408083208a845282528083208054600160a060020a03191690558c835260029091528082209650610dd6928b9290891691633fa4f245919051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610db657600080fd5b6102c65a03f11515610dc757600080fd5b50505060405180519050611edb565b925084600160a060020a031663b0c8097284600160405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b1515610e2757600080fd5b6102c65a03f11515610e3857600080fd5b505050610e44896114da565b91506002826005811115610e5457fe5b1415610ef25784600160a060020a031663bbe42771600560405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610ea157600080fd5b6102c65a03f11515610eb257600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600160405191825260ff1660208201526040908101905180910390a3611249565b6004826005811115610f0057fe5b14610f0a57600080fd5b662386f26fc10000831080610f88575060018401546202a2ff1901600160a060020a0386166305b344106000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610f6b57600080fd5b6102c65a03f11515610f7c57600080fd5b50505060405180519050115b156110265784600160a060020a031663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610fd557600080fd5b6102c65a03f11515610fe657600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600060405191825260ff1660208201526040908101905180910390a3611249565b8360030154831115611108578354600160a060020a0316156110a257508254600160a060020a03168063bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b151561108d57600080fd5b6102c65a03f1151561109e57600080fd5b5050505b600384018054600280870191909155908490558454600160a060020a031916600160a060020a038781169190911786553316908a9060008051602061269483398151915290869060405191825260ff1660208201526040908101905180910390a3611249565b83600201548311156111b45760028401839055600160a060020a03851663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b151561116357600080fd5b6102c65a03f1151561117457600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600360405191825260ff1660208201526040908101905180910390a3611249565b84600160a060020a031663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156111fc57600080fd5b6102c65a03f1151561120d57600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600460405191825260ff1660208201526040908101905180910390a35b505050505050505050565b600080826002611263826114da565b600581111561126e57fe5b1415806112fa575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156112c957600080fd5b6102c65a03f115156112da57600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b1561130457600080fd5b60008054600154600160a060020a03909116916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561135b57600080fd5b6102c65a03f1151561136c57600080fd5b50505060405180519050925030600160a060020a031683600160a060020a0316141561139757600080fd5b600084815260026020526040908190208054909350600160a060020a03169063faab9d399085905160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b15156113fa57600080fd5b6102c65a03f1151561140b57600080fd5b505082546001840154600160a060020a03808716935063ea9e107a92889291169060405160e060020a63ffffffff86160281526004810193909352600160a060020a0390911660248301526044820152606401600060405180830381600087803b151561147757600080fd5b6102c65a03f1151561148857600080fd5b50508254600160a060020a03191683555050600060018201819055600282018190556003909101555050565b6003602090815260009283526040808420909152908252902054600160a060020a031681565b60008181526002602052604081206114f2834261169b565b1515611501576005915061154a565b80600101544210156115315760018101546202a2ff1901421015611528576001915061154a565b6004915061154a565b60038101541515611545576000915061154a565b600291505b50919050565b600082600261155e826114da565b600581111561156957fe5b1415806115f5575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156115c457600080fd5b6102c65a03f115156115d557600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b156115ff57600080fd5b600160a060020a038316151561161457600080fd5b600084815260026020526040908190208054909350600160a060020a0316906313af40359085905160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b151561167757600080fd5b6102c65a03f1151561168857600080fd5b5050506116958484611eec565b50505050565b60006116a68361072a565b821190505b92915050565b60008160026116bf826114da565b60058111156116ca57fe5b141580611756575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561172557600080fd5b6102c65a03f1151561173657600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b1561176057600080fd5b60008381526002602081905260409091209081015490925061178990662386f26fc10000611ec3565b600283018190558254600160a060020a03169063b0c8097290600160405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b15156117e157600080fd5b6102c65a03f115156117f257600080fd5b5050825461186291508490600160a060020a0316638da5cb5b6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561184257600080fd5b6102c65a03f1151561185357600080fd5b50505060405180519050611eec565b8154600160a060020a0316638da5cb5b6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156118a957600080fd5b6102c65a03f115156118ba57600080fd5b50505060405180519050600160a060020a031683600019167f0f0c27adfd84b60b6f456b0e87cdccb1e5fb9603991588d87fa99f5b6b61e6708460020154856001015460405191825260208201526040908101905180910390a3505050565b60045481565b6249d40081565b600160a060020a0333811660009081526003602090815260408083208584529091528120549091168190111561195b57600080fd5b662386f26fc1000034101561196f57600080fd5b3433611979612187565b600160a060020a0390911681526020016040518091039082f080151561199e57600080fd5b33600160a060020a039081166000818152600360209081526040808320898452909152908190208054600160a060020a0319169385169390931790925591935090915083907fb556ff269c1b6714f432c36431e2041d28436a73b6c3f19c021827bbdc6bfc299034905190815260200160405180910390a35050565b80511515611a2757600080fd5b6002611a4b82600184510381518110611a3c57fe5b906020019060200201516114da565b6005811115611a5657fe5b1415611a6157600080fd5b611a72600182510382600154611fd6565b50565b60005b8151811015611aa757611a9f828281518110611a9057fe5b90602001906020020151611ab0565b600101611a78565b5050565b505050565b600080600454421080611aca5750600454630784ce000142115b80611b51575060008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611b2a57600080fd5b6102c65a03f11515611b3b57600080fd5b50505060405180519050600160a060020a031614155b15611b5b57600080fd5b611b64836114da565b91506001826005811115611b7457fe5b1415611b7f57611aab565b6000826005811115611b8d57fe5b14611b9757600080fd5b50600082815260026020819052604080832042620697800160018201819055928101849055600381019390935584917f87e97e825a1d1fa0c54e1d36c7506c1dea8b1efd451fe68b000cf96f7cf40003915190815260200160405180910390a2505050565b60015481565b611c0b82611a75565b611aa781611926565b60008054600154600160a060020a033081169216906302571be390846040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611c6d57600080fd5b6102c65a03f11515611c7e57600080fd5b50505060405180519050600160a060020a03161415611aa757600054600154600160a060020a03909116906306ab592390843060405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b1515611cfd57600080fd5b6102c65a03f11515611d0e57600080fd5b5050506001548260405191825260208201526040908101905190819003902060008054919250600160a060020a0390911690631896f70a90839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b1515611d8c57600080fd5b6102c65a03f11515611d9d57600080fd5b505060008054600160a060020a03169150635b0fc9c390839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b1515611dfa57600080fd5b6102c65a03f11515611e0b57600080fd5b5050505050565b600060018201818080838651019250600091505b82841015611eba5760ff845116905060808160ff161015611e4c57600184019350611eaf565b60e08160ff161015611e6357600284019350611eaf565b60f08160ff161015611e7a57600384019350611eaf565b60f88160ff161015611e9157600484019350611eaf565b60fc8160ff161015611ea857600584019350611eaf565b6006840193505b600190910190611e26565b50949350505050565b600081831115611ed45750816116ab565b50806116ab565b600081831015611ed45750816116ab565b60008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611f4657600080fd5b6102c65a03f11515611f5757600080fd5b50505060405180519050600160a060020a03161415611aa757600054600154600160a060020a03909116906306ab592390848460405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b1515611dfa57600080fd5b600054600160a060020a03166306ab592382848681518110611ff457fe5b906020019060200201513060405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b151561204b57600080fd5b6102c65a03f1151561205c57600080fd5b5050508082848151811061206c57fe5b906020019060200201516040519182526020820152604090810190518091039020905060008311156120a6576120a6600184038383611fd6565b60008054600160a060020a031690631896f70a90839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b151561210057600080fd5b6102c65a03f1151561211157600080fd5b505060008054600160a060020a03169150635b0fc9c390839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b151561216e57600080fd5b6102c65a03f1151561217f57600080fd5b505050505050565b6040516104fc8061219883390190560060606040526040516020806104fc8339810160405280805160028054600160a060020a03928316600160a060020a03199182161790915560008054339093169290911691909117905550504260019081556005805460ff191690911790553460045561048c806100706000396000f300606060405236156100a15763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305b3441081146100a65780630b5ab3d5146100cb57806313af4035146100e05780632b20e397146100ff5780633fa4f2451461012e578063674f220f146101415780638da5cb5b14610154578063b0c8097214610167578063bbe4277114610182578063faab9d3914610198575b600080fd5b34156100b157600080fd5b6100b96101b7565b60405190815260200160405180910390f35b34156100d657600080fd5b6100de6101bd565b005b34156100eb57600080fd5b6100de600160a060020a0360043516610207565b341561010a57600080fd5b6101126102b0565b604051600160a060020a03909116815260200160405180910390f35b341561013957600080fd5b6100b96102bf565b341561014c57600080fd5b6101126102c5565b341561015f57600080fd5b6101126102d4565b341561017257600080fd5b6100de60043560243515156102e3565b341561018d57600080fd5b6100de60043561036c565b34156101a357600080fd5b6100de600160a060020a0360043516610416565b60015481565b60055460ff16156101cd57600080fd5b600254600160a060020a039081169030163180156108fc0290604051600060405180830381858888f19350505050156102055761deadff5b565b60005433600160a060020a0390811691161461022257600080fd5b600160a060020a038116151561023757600080fd5b6002805460038054600160a060020a0380841673ffffffffffffffffffffffffffffffffffffffff19928316179092559091169083161790557fa2ea9883a321a3e97b8266c2b078bfeec6d50c711ed71f874a90d500ae2eaf3681604051600160a060020a03909116815260200160405180910390a150565b600054600160a060020a031681565b60045481565b600354600160a060020a031681565b600254600160a060020a031681565b60005433600160a060020a039081169116146102fe57600080fd5b60055460ff16151561030f57600080fd5b81600454101561031e57600080fd5b6004829055600254600160a060020a039081169030163183900380156108fc0290604051600060405180830381858888f1935050505015801561035e5750805b1561036857600080fd5b5050565b60005433600160a060020a0390811691161461038757600080fd5b60055460ff16151561039857600080fd5b6005805460ff1916905561dead6103e8600160a060020a03301631838203020480156108fc0290604051600060405180830381858888f1935050505015156103df57600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a5c6223eabea1077be696b3f265cf1360405160405180910390a16104136101bd565b50565b60005433600160a060020a0390811691161461043157600080fd5b6000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03929092169190911790555600a165627a7a7230582023849fab751378a237489f526a289ede7796b7f6b7dac5a973b8c3ca25f368a800297b6c4b278d165a6b33958f8ea5dfb00c8c9d4d0acf1985bef5d10786898bc3e7a165627a7a72305820e6807b87ab11a69864cefed52eef7f9c4635fd0e26312e944bbbcbff5cd26d920029" registrar_bytecode_runtime = "606060405236156101175763ffffffff60e060020a6000350416630230a07c811461011c57806313c89a8f1461013457806315f733311461015c57806322ec1244146101ad5780632525f5c1146101d5578063267b6922146101f75780633f15457f1461025f57806347872b421461028e5780635ddae283146102aa5780635e431709146102c057806361d585da146102e257806379ce9fac1461031c578063935033371461033e578063983b94fb1461036b5780639c67f06f14610381578063ae1a0b0c14610394578063ce92dced146103c0578063de10f04b146103cb578063e27fe50f1461041a578063ea9e107a14610469578063ede8acdb1461048e578063faff50a8146104a4578063febefd61146104b7575b600080fd5b341561012757600080fd5b6101326004356104fd565b005b341561013f57600080fd5b61014a60043561072a565b60405190815260200160405180910390f35b341561016757600080fd5b61013260046024813581810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284375094965061074e95505050505050565b34156101b857600080fd5b61014a600435600160a060020a0360243516604435606435610a7a565b34156101e057600080fd5b610132600160a060020a0360043516602435610ac5565b341561020257600080fd5b61020d600435610c8c565b6040518086600581111561021d57fe5b60ff16815260200185600160a060020a0316600160a060020a031681526020018481526020018381526020018281526020019550505050505060405180910390f35b341561026a57600080fd5b610272610cd8565b604051600160a060020a03909116815260200160405180910390f35b341561029957600080fd5b610132600435602435604435610ce7565b34156102b557600080fd5b610132600435611254565b34156102cb57600080fd5b610272600160a060020a03600435166024356114b4565b34156102ed57600080fd5b6102f86004356114da565b6040518082600581111561030857fe5b60ff16815260200191505060405180910390f35b341561032757600080fd5b610132600435600160a060020a0360243516611550565b341561034957600080fd5b61035760043560243561169b565b604051901515815260200160405180910390f35b341561037657600080fd5b6101326004356116b1565b341561038c57600080fd5b61014a611919565b341561039f57600080fd5b6103a761191f565b60405163ffffffff909116815260200160405180910390f35b610132600435611926565b34156103d657600080fd5b6101326004602481358181019083013580602081810201604051908101604052809392919081815260200183836020028082843750949650611a1a95505050505050565b341561042557600080fd5b6101326004602481358181019083013580602081810201604051908101604052809392919081815260200183836020028082843750949650611a7595505050505050565b341561047457600080fd5b610132600435600160a060020a0360243516604435611aab565b341561049957600080fd5b610132600435611ab0565b34156104af57600080fd5b61014a611bfc565b61013260046024813581810190830135806020818102016040519081016040528093929190818152602001838360200280828437509496505093359350611c0292505050565b60008082600261050c826114da565b600581111561051757fe5b1415806105a3575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561057257600080fd5b6102c65a03f1151561058357600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b156105ad57600080fd5b600084815260026020526040902080546001820154919450600160a060020a031692506301e13380014210801561065f575060008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561063957600080fd5b6102c65a03f1151561064a57600080fd5b50505060405180519050600160a060020a0316145b1561066957600080fd5b60006002840181905560038401558254600160a060020a031916835561068e84611c14565b81600160a060020a031663bbe427716103e860405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156106d657600080fd5b6102c65a03f115156106e757600080fd5b505050600283015484907f292b79b9246fa2c8e77d3fe195b251f9cb839d7d038e667c069ee7708c631e169060405190815260200160405180910390a250505050565b6004547001000000000000000000000000000000006249d400818404020401919050565b600080826040518082805190602001908083835b602083106107815780518252601f199092019160209182019101610762565b6001836020036101000a03801982511681845116179092525050509190910192506040915050519081900390206002806107ba836114da565b60058111156107c557fe5b146107cf57600080fd5b60066107da86611e12565b11156107e557600080fd5b846040518082805190602001908083835b602083106108155780518252601f1990920191602091820191016107f6565b6001836020036101000a03801982511681845116179092525050509190910192506040915050519081900390206000818152600260205260409020909450925061085e84611c14565b8254600160a060020a0316156109b5576108838360020154662386f26fc10000611ec3565b60028085018290558454600160a060020a03169163b0c80972919004600060405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b15156108de57600080fd5b6102c65a03f115156108ef57600080fd5b50508354600160a060020a031690506313af40353360405160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b151561094257600080fd5b6102c65a03f1151561095357600080fd5b50508354600160a060020a0316905063bbe427716103e860405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156109a057600080fd5b6102c65a03f115156109b157600080fd5b5050505b846040518082805190602001908083835b602083106109e55780518252601f1990920191602091820191016109c6565b6001836020036101000a0380198251168184511617909252505050919091019250604091505051809103902084600019167f1f9c649fe47e58bb60f4e52f0d90e4c47a526c9f90c5113df842c025970b66ad8560020154866001015460405191825260208201526040908101905180910390a3505060006002820181905560038201558054600160a060020a03191690555050565b600084848484604051938452600160a060020a03929092166c010000000000000000000000000260208401526034830152605482015260740160405180910390209050949350505050565b600160a060020a03808316600090815260036020908152604080832085845290915290205416801580610b61575062069780600160a060020a0382166305b344106000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610b3d57600080fd5b6102c65a03f11515610b4e57600080fd5b5050506040518051905001621275000142105b15610b6b57600080fd5b80600160a060020a03166313af40353360405160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b1515610bb957600080fd5b6102c65a03f11515610bca57600080fd5b50505080600160a060020a031663bbe42771600560405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610c1457600080fd5b6102c65a03f11515610c2557600080fd5b505050600160a060020a03831660008181526003602090815260408083208684529091528082208054600160a060020a03191690558491600080516020612694833981519152916005905191825260ff1660208201526040908101905180910390a3505050565b60008181526002602052604081208190819081908190610cab876114da565b815460018301546002840154600390940154929a600160a060020a03909216995097509195509350915050565b600054600160a060020a031681565b600080600080600080610cfc89338a8a610a7a565b600160a060020a033381166000908152600360209081526040808320858452909152902054919750169450841515610d3357600080fd5b600160a060020a0333811660009081526003602090815260408083208a845282528083208054600160a060020a03191690558c835260029091528082209650610dd6928b9290891691633fa4f245919051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610db657600080fd5b6102c65a03f11515610dc757600080fd5b50505060405180519050611edb565b925084600160a060020a031663b0c8097284600160405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b1515610e2757600080fd5b6102c65a03f11515610e3857600080fd5b505050610e44896114da565b91506002826005811115610e5457fe5b1415610ef25784600160a060020a031663bbe42771600560405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610ea157600080fd5b6102c65a03f11515610eb257600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600160405191825260ff1660208201526040908101905180910390a3611249565b6004826005811115610f0057fe5b14610f0a57600080fd5b662386f26fc10000831080610f88575060018401546202a2ff1901600160a060020a0386166305b344106000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610f6b57600080fd5b6102c65a03f11515610f7c57600080fd5b50505060405180519050115b156110265784600160a060020a031663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b1515610fd557600080fd5b6102c65a03f11515610fe657600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600060405191825260ff1660208201526040908101905180910390a3611249565b8360030154831115611108578354600160a060020a0316156110a257508254600160a060020a03168063bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b151561108d57600080fd5b6102c65a03f1151561109e57600080fd5b5050505b600384018054600280870191909155908490558454600160a060020a031916600160a060020a038781169190911786553316908a9060008051602061269483398151915290869060405191825260ff1660208201526040908101905180910390a3611249565b83600201548311156111b45760028401839055600160a060020a03851663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b151561116357600080fd5b6102c65a03f1151561117457600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600360405191825260ff1660208201526040908101905180910390a3611249565b84600160a060020a031663bbe427716103e360405160e060020a63ffffffff84160281526004810191909152602401600060405180830381600087803b15156111fc57600080fd5b6102c65a03f1151561120d57600080fd5b5050600160a060020a03331690508960008051602061269483398151915285600460405191825260ff1660208201526040908101905180910390a35b505050505050505050565b600080826002611263826114da565b600581111561126e57fe5b1415806112fa575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156112c957600080fd5b6102c65a03f115156112da57600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b1561130457600080fd5b60008054600154600160a060020a03909116916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561135b57600080fd5b6102c65a03f1151561136c57600080fd5b50505060405180519050925030600160a060020a031683600160a060020a0316141561139757600080fd5b600084815260026020526040908190208054909350600160a060020a03169063faab9d399085905160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b15156113fa57600080fd5b6102c65a03f1151561140b57600080fd5b505082546001840154600160a060020a03808716935063ea9e107a92889291169060405160e060020a63ffffffff86160281526004810193909352600160a060020a0390911660248301526044820152606401600060405180830381600087803b151561147757600080fd5b6102c65a03f1151561148857600080fd5b50508254600160a060020a03191683555050600060018201819055600282018190556003909101555050565b6003602090815260009283526040808420909152908252902054600160a060020a031681565b60008181526002602052604081206114f2834261169b565b1515611501576005915061154a565b80600101544210156115315760018101546202a2ff1901421015611528576001915061154a565b6004915061154a565b60038101541515611545576000915061154a565b600291505b50919050565b600082600261155e826114da565b600581111561156957fe5b1415806115f5575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156115c457600080fd5b6102c65a03f115156115d557600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b156115ff57600080fd5b600160a060020a038316151561161457600080fd5b600084815260026020526040908190208054909350600160a060020a0316906313af40359085905160e060020a63ffffffff8416028152600160a060020a039091166004820152602401600060405180830381600087803b151561167757600080fd5b6102c65a03f1151561168857600080fd5b5050506116958484611eec565b50505050565b60006116a68361072a565b821190505b92915050565b60008160026116bf826114da565b60058111156116ca57fe5b141580611756575060008181526002602052604080822054600160a060020a031691638da5cb5b9151602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561172557600080fd5b6102c65a03f1151561173657600080fd5b50505060405180519050600160a060020a031633600160a060020a031614155b1561176057600080fd5b60008381526002602081905260409091209081015490925061178990662386f26fc10000611ec3565b600283018190558254600160a060020a03169063b0c8097290600160405160e060020a63ffffffff8516028152600481019290925215156024820152604401600060405180830381600087803b15156117e157600080fd5b6102c65a03f115156117f257600080fd5b5050825461186291508490600160a060020a0316638da5cb5b6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561184257600080fd5b6102c65a03f1151561185357600080fd5b50505060405180519050611eec565b8154600160a060020a0316638da5cb5b6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156118a957600080fd5b6102c65a03f115156118ba57600080fd5b50505060405180519050600160a060020a031683600019167f0f0c27adfd84b60b6f456b0e87cdccb1e5fb9603991588d87fa99f5b6b61e6708460020154856001015460405191825260208201526040908101905180910390a3505050565b60045481565b6249d40081565b600160a060020a0333811660009081526003602090815260408083208584529091528120549091168190111561195b57600080fd5b662386f26fc1000034101561196f57600080fd5b3433611979612187565b600160a060020a0390911681526020016040518091039082f080151561199e57600080fd5b33600160a060020a039081166000818152600360209081526040808320898452909152908190208054600160a060020a0319169385169390931790925591935090915083907fb556ff269c1b6714f432c36431e2041d28436a73b6c3f19c021827bbdc6bfc299034905190815260200160405180910390a35050565b80511515611a2757600080fd5b6002611a4b82600184510381518110611a3c57fe5b906020019060200201516114da565b6005811115611a5657fe5b1415611a6157600080fd5b611a72600182510382600154611fd6565b50565b60005b8151811015611aa757611a9f828281518110611a9057fe5b90602001906020020151611ab0565b600101611a78565b5050565b505050565b600080600454421080611aca5750600454630784ce000142115b80611b51575060008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611b2a57600080fd5b6102c65a03f11515611b3b57600080fd5b50505060405180519050600160a060020a031614155b15611b5b57600080fd5b611b64836114da565b91506001826005811115611b7457fe5b1415611b7f57611aab565b6000826005811115611b8d57fe5b14611b9757600080fd5b50600082815260026020819052604080832042620697800160018201819055928101849055600381019390935584917f87e97e825a1d1fa0c54e1d36c7506c1dea8b1efd451fe68b000cf96f7cf40003915190815260200160405180910390a2505050565b60015481565b611c0b82611a75565b611aa781611926565b60008054600154600160a060020a033081169216906302571be390846040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611c6d57600080fd5b6102c65a03f11515611c7e57600080fd5b50505060405180519050600160a060020a03161415611aa757600054600154600160a060020a03909116906306ab592390843060405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b1515611cfd57600080fd5b6102c65a03f11515611d0e57600080fd5b5050506001548260405191825260208201526040908101905190819003902060008054919250600160a060020a0390911690631896f70a90839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b1515611d8c57600080fd5b6102c65a03f11515611d9d57600080fd5b505060008054600160a060020a03169150635b0fc9c390839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b1515611dfa57600080fd5b6102c65a03f11515611e0b57600080fd5b5050505050565b600060018201818080838651019250600091505b82841015611eba5760ff845116905060808160ff161015611e4c57600184019350611eaf565b60e08160ff161015611e6357600284019350611eaf565b60f08160ff161015611e7a57600384019350611eaf565b60f88160ff161015611e9157600484019350611eaf565b60fc8160ff161015611ea857600584019350611eaf565b6006840193505b600190910190611e26565b50949350505050565b600081831115611ed45750816116ab565b50806116ab565b600081831015611ed45750816116ab565b60008054600154600160a060020a03308116939216916302571be391906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515611f4657600080fd5b6102c65a03f11515611f5757600080fd5b50505060405180519050600160a060020a03161415611aa757600054600154600160a060020a03909116906306ab592390848460405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b1515611dfa57600080fd5b600054600160a060020a03166306ab592382848681518110611ff457fe5b906020019060200201513060405160e060020a63ffffffff861602815260048101939093526024830191909152600160a060020a03166044820152606401600060405180830381600087803b151561204b57600080fd5b6102c65a03f1151561205c57600080fd5b5050508082848151811061206c57fe5b906020019060200201516040519182526020820152604090810190518091039020905060008311156120a6576120a6600184038383611fd6565b60008054600160a060020a031690631896f70a90839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b151561210057600080fd5b6102c65a03f1151561211157600080fd5b505060008054600160a060020a03169150635b0fc9c390839060405160e060020a63ffffffff85160281526004810192909252600160a060020a03166024820152604401600060405180830381600087803b151561216e57600080fd5b6102c65a03f1151561217f57600080fd5b505050505050565b6040516104fc8061219883390190560060606040526040516020806104fc8339810160405280805160028054600160a060020a03928316600160a060020a03199182161790915560008054339093169290911691909117905550504260019081556005805460ff191690911790553460045561048c806100706000396000f300606060405236156100a15763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305b3441081146100a65780630b5ab3d5146100cb57806313af4035146100e05780632b20e397146100ff5780633fa4f2451461012e578063674f220f146101415780638da5cb5b14610154578063b0c8097214610167578063bbe4277114610182578063faab9d3914610198575b600080fd5b34156100b157600080fd5b6100b96101b7565b60405190815260200160405180910390f35b34156100d657600080fd5b6100de6101bd565b005b34156100eb57600080fd5b6100de600160a060020a0360043516610207565b341561010a57600080fd5b6101126102b0565b604051600160a060020a03909116815260200160405180910390f35b341561013957600080fd5b6100b96102bf565b341561014c57600080fd5b6101126102c5565b341561015f57600080fd5b6101126102d4565b341561017257600080fd5b6100de60043560243515156102e3565b341561018d57600080fd5b6100de60043561036c565b34156101a357600080fd5b6100de600160a060020a0360043516610416565b60015481565b60055460ff16156101cd57600080fd5b600254600160a060020a039081169030163180156108fc0290604051600060405180830381858888f19350505050156102055761deadff5b565b60005433600160a060020a0390811691161461022257600080fd5b600160a060020a038116151561023757600080fd5b6002805460038054600160a060020a0380841673ffffffffffffffffffffffffffffffffffffffff19928316179092559091169083161790557fa2ea9883a321a3e97b8266c2b078bfeec6d50c711ed71f874a90d500ae2eaf3681604051600160a060020a03909116815260200160405180910390a150565b600054600160a060020a031681565b60045481565b600354600160a060020a031681565b600254600160a060020a031681565b60005433600160a060020a039081169116146102fe57600080fd5b60055460ff16151561030f57600080fd5b81600454101561031e57600080fd5b6004829055600254600160a060020a039081169030163183900380156108fc0290604051600060405180830381858888f1935050505015801561035e5750805b1561036857600080fd5b5050565b60005433600160a060020a0390811691161461038757600080fd5b60055460ff16151561039857600080fd5b6005805460ff1916905561dead6103e8600160a060020a03301631838203020480156108fc0290604051600060405180830381858888f1935050505015156103df57600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a5c6223eabea1077be696b3f265cf1360405160405180910390a16104136101bd565b50565b60005433600160a060020a0390811691161461043157600080fd5b6000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03929092169190911790555600a165627a7a7230582023849fab751378a237489f526a289ede7796b7f6b7dac5a973b8c3ca25f368a800297b6c4b278d165a6b33958f8ea5dfb00c8c9d4d0acf1985bef5d10786898bc3e7a165627a7a72305820e6807b87ab11a69864cefed52eef7f9c4635fd0e26312e944bbbcbff5cd26d920029" resolver_abi = json.loads('[{"constant":true,"inputs":[{"name":"interfaceID","type":"bytes4"}],"name":"supportsInterface","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"key","type":"string"},{"name":"value","type":"string"}],"name":"setText","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"},{"name":"contentTypes","type":"uint256"}],"name":"ABI","outputs":[{"name":"contentType","type":"uint256"},{"name":"data","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"x","type":"bytes32"},{"name":"y","type":"bytes32"}],"name":"setPubkey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"content","outputs":[{"name":"ret","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"addr","outputs":[{"name":"ret","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"},{"name":"key","type":"string"}],"name":"text","outputs":[{"name":"ret","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"contentType","type":"uint256"},{"name":"data","type":"bytes"}],"name":"setABI","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"name","outputs":[{"name":"ret","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"name","type":"string"}],"name":"setName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"hash","type":"bytes32"}],"name":"setContent","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"pubkey","outputs":[{"name":"x","type":"bytes32"},{"name":"y","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"addr","type":"address"}],"name":"setAddr","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"ensAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"a","type":"address"}],"name":"AddrChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"hash","type":"bytes32"}],"name":"ContentChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"name","type":"string"}],"name":"NameChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":true,"name":"contentType","type":"uint256"}],"name":"ABIChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"x","type":"bytes32"},{"indexed":false,"name":"y","type":"bytes32"}],"name":"PubkeyChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":true,"name":"indexedKey","type":"string"},{"indexed":false,"name":"key","type":"string"}],"name":"TextChanged","type":"event"}]') resolver_bytecode = "6060604052341561000f57600080fd5b6040516020806111b08339810160405280805160008054600160a060020a03909216600160a060020a0319909216919091179055505061115c806100546000396000f300606060405236156100a95763ffffffff60e060020a60003504166301ffc9a781146100ae57806310f13a8c146100e25780632203ab561461017c57806329cd62ea146102135780632dff69411461022f5780633b3b57de1461025757806359d1d43c14610289578063623195b014610356578063691f3431146103b257806377372213146103c8578063c3d014d61461041e578063c869023314610437578063d5fa2b0014610465575b600080fd5b34156100b957600080fd5b6100ce600160e060020a031960043516610487565b604051901515815260200160405180910390f35b34156100ed57600080fd5b61017a600480359060446024803590810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405281815292919060208401838380828437509496506105f495505050505050565b005b341561018757600080fd5b610195600435602435610805565b60405182815260406020820181815290820183818151815260200191508051906020019080838360005b838110156101d75780820151838201526020016101bf565b50505050905090810190601f1680156102045780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b341561021e57600080fd5b61017a60043560243560443561092f565b341561023a57600080fd5b610245600435610a2e565b60405190815260200160405180910390f35b341561026257600080fd5b61026d600435610a44565b604051600160a060020a03909116815260200160405180910390f35b341561029457600080fd5b6102df600480359060446024803590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610a5f95505050505050565b60405160208082528190810183818151815260200191508051906020019080838360005b8381101561031b578082015183820152602001610303565b50505050905090810190601f1680156103485780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561036157600080fd5b61017a600480359060248035919060649060443590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610b7e95505050505050565b34156103bd57600080fd5b6102df600435610c7a565b34156103d357600080fd5b61017a600480359060446024803590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610d4095505050505050565b341561042957600080fd5b61017a600435602435610e8a565b341561044257600080fd5b61044d600435610f63565b60405191825260208201526040908101905180910390f35b341561047057600080fd5b61017a600435600160a060020a0360243516610f80565b6000600160e060020a031982167f3b3b57de0000000000000000000000000000000000000000000000000000000014806104ea5750600160e060020a031982167fd8389dc500000000000000000000000000000000000000000000000000000000145b8061051e5750600160e060020a031982167f691f343100000000000000000000000000000000000000000000000000000000145b806105525750600160e060020a031982167f2203ab5600000000000000000000000000000000000000000000000000000000145b806105865750600160e060020a031982167fc869023300000000000000000000000000000000000000000000000000000000145b806105ba5750600160e060020a031982167f59d1d43c00000000000000000000000000000000000000000000000000000000145b806105ee5750600160e060020a031982167f01ffc9a700000000000000000000000000000000000000000000000000000000145b92915050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561064d57600080fd5b6102c65a03f1151561065e57600080fd5b50505060405180519050600160a060020a031614151561067d57600080fd5b6000848152600160205260409081902083916005909101908590518082805190602001908083835b602083106106c45780518252601f1990920191602091820191016106a5565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020908051610708929160200190611083565b50826040518082805190602001908083835b602083106107395780518252601f19909201916020918201910161071a565b6001836020036101000a0380198251168184511617909252505050919091019250604091505051908190039020847fd8c9334b1a9c2f9da342a0a2b32629c1a229b6445dad78947f674b44444a75508560405160208082528190810183818151815260200191508051906020019080838360005b838110156107c55780820151838201526020016107ad565b50505050905090810190601f1680156107f25780820380516001836020036101000a031916815260200191505b509250505060405180910390a350505050565b600061080f611101565b60008481526001602081905260409091209092505b838311610922578284161580159061085d5750600083815260068201602052604081205460026000196101006001841615020190911604115b15610917578060060160008481526020019081526020016000208054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561090b5780601f106108e05761010080835404028352916020019161090b565b820191906000526020600020905b8154815290600101906020018083116108ee57829003601f168201915b50505050509150610927565b600290920291610824565b600092505b509250929050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561098857600080fd5b6102c65a03f1151561099957600080fd5b50505060405180519050600160a060020a03161415156109b857600080fd5b6040805190810160409081528482526020808301859052600087815260019091522060030181518155602082015160019091015550837f1d6f5e03d3f63eb58751986629a5439baee5079ff04f345becb66e23eb154e46848460405191825260208201526040908101905180910390a250505050565b6000908152600160208190526040909120015490565b600090815260016020526040902054600160a060020a031690565b610a67611101565b60008381526001602052604090819020600501908390518082805190602001908083835b60208310610aaa5780518252601f199092019160209182019101610a8b565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390208054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610b715780601f10610b4657610100808354040283529160200191610b71565b820191906000526020600020905b815481529060010190602001808311610b5457829003601f168201915b5050505050905092915050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610bd757600080fd5b6102c65a03f11515610be857600080fd5b50505060405180519050600160a060020a0316141515610c0757600080fd5b6000198301831615610c1857600080fd5b60008481526001602090815260408083208684526006019091529020828051610c45929160200190611083565b5082847faa121bbeef5f32f5961a2a28966e769023910fc9479059ee3495d4c1a696efe360405160405180910390a350505050565b610c82611101565b6001600083600019166000191681526020019081526020016000206002018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610d345780601f10610d0957610100808354040283529160200191610d34565b820191906000526020600020905b815481529060010190602001808311610d1757829003601f168201915b50505050509050919050565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610d9957600080fd5b6102c65a03f11515610daa57600080fd5b50505060405180519050600160a060020a0316141515610dc957600080fd5b6000838152600160205260409020600201828051610deb929160200190611083565b50827fb7d29e911041e8d9b843369e890bcb72c9388692ba48b65ac54e7214c4c348f78360405160208082528190810183818151815260200191508051906020019080838360005b83811015610e4b578082015183820152602001610e33565b50505050905090810190601f168015610e785780820380516001836020036101000a031916815260200191505b509250505060405180910390a2505050565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610ee357600080fd5b6102c65a03f11515610ef457600080fd5b50505060405180519050600160a060020a0316141515610f1357600080fd5b6000838152600160208190526040918290200183905583907f0424b6fe0d9c3bdbece0e7879dc241bb0c22e900be8b6c168b4ee08bd9bf83bc9084905190815260200160405180910390a2505050565b600090815260016020526040902060038101546004909101549091565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610fd957600080fd5b6102c65a03f11515610fea57600080fd5b50505060405180519050600160a060020a031614151561100957600080fd5b60008381526001602052604090819020805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03851617905583907f52d7d861f09ab3d26239d492e8968629f95e9e318cf0b73bfddc441522a15fd290849051600160a060020a03909116815260200160405180910390a2505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106110c457805160ff19168380011785556110f1565b828001600101855582156110f1579182015b828111156110f15782518255916020019190600101906110d6565b506110fd929150611113565b5090565b60206040519081016040526000815290565b61112d91905b808211156110fd5760008155600101611119565b905600a165627a7a723058206016a807d9d5f6060e9c0d1c808e52d4ca30a4cab0140adcc6587bfc13bedf100029" resolver_bytecode_runtime = "606060405236156100a95763ffffffff60e060020a60003504166301ffc9a781146100ae57806310f13a8c146100e25780632203ab561461017c57806329cd62ea146102135780632dff69411461022f5780633b3b57de1461025757806359d1d43c14610289578063623195b014610356578063691f3431146103b257806377372213146103c8578063c3d014d61461041e578063c869023314610437578063d5fa2b0014610465575b600080fd5b34156100b957600080fd5b6100ce600160e060020a031960043516610487565b604051901515815260200160405180910390f35b34156100ed57600080fd5b61017a600480359060446024803590810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405281815292919060208401838380828437509496506105f495505050505050565b005b341561018757600080fd5b610195600435602435610805565b60405182815260406020820181815290820183818151815260200191508051906020019080838360005b838110156101d75780820151838201526020016101bf565b50505050905090810190601f1680156102045780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b341561021e57600080fd5b61017a60043560243560443561092f565b341561023a57600080fd5b610245600435610a2e565b60405190815260200160405180910390f35b341561026257600080fd5b61026d600435610a44565b604051600160a060020a03909116815260200160405180910390f35b341561029457600080fd5b6102df600480359060446024803590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610a5f95505050505050565b60405160208082528190810183818151815260200191508051906020019080838360005b8381101561031b578082015183820152602001610303565b50505050905090810190601f1680156103485780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561036157600080fd5b61017a600480359060248035919060649060443590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610b7e95505050505050565b34156103bd57600080fd5b6102df600435610c7a565b34156103d357600080fd5b61017a600480359060446024803590810190830135806020601f82018190048102016040519081016040528181529291906020840183838082843750949650610d4095505050505050565b341561042957600080fd5b61017a600435602435610e8a565b341561044257600080fd5b61044d600435610f63565b60405191825260208201526040908101905180910390f35b341561047057600080fd5b61017a600435600160a060020a0360243516610f80565b6000600160e060020a031982167f3b3b57de0000000000000000000000000000000000000000000000000000000014806104ea5750600160e060020a031982167fd8389dc500000000000000000000000000000000000000000000000000000000145b8061051e5750600160e060020a031982167f691f343100000000000000000000000000000000000000000000000000000000145b806105525750600160e060020a031982167f2203ab5600000000000000000000000000000000000000000000000000000000145b806105865750600160e060020a031982167fc869023300000000000000000000000000000000000000000000000000000000145b806105ba5750600160e060020a031982167f59d1d43c00000000000000000000000000000000000000000000000000000000145b806105ee5750600160e060020a031982167f01ffc9a700000000000000000000000000000000000000000000000000000000145b92915050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561064d57600080fd5b6102c65a03f1151561065e57600080fd5b50505060405180519050600160a060020a031614151561067d57600080fd5b6000848152600160205260409081902083916005909101908590518082805190602001908083835b602083106106c45780518252601f1990920191602091820191016106a5565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020908051610708929160200190611083565b50826040518082805190602001908083835b602083106107395780518252601f19909201916020918201910161071a565b6001836020036101000a0380198251168184511617909252505050919091019250604091505051908190039020847fd8c9334b1a9c2f9da342a0a2b32629c1a229b6445dad78947f674b44444a75508560405160208082528190810183818151815260200191508051906020019080838360005b838110156107c55780820151838201526020016107ad565b50505050905090810190601f1680156107f25780820380516001836020036101000a031916815260200191505b509250505060405180910390a350505050565b600061080f611101565b60008481526001602081905260409091209092505b838311610922578284161580159061085d5750600083815260068201602052604081205460026000196101006001841615020190911604115b15610917578060060160008481526020019081526020016000208054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561090b5780601f106108e05761010080835404028352916020019161090b565b820191906000526020600020905b8154815290600101906020018083116108ee57829003601f168201915b50505050509150610927565b600290920291610824565b600092505b509250929050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561098857600080fd5b6102c65a03f1151561099957600080fd5b50505060405180519050600160a060020a03161415156109b857600080fd5b6040805190810160409081528482526020808301859052600087815260019091522060030181518155602082015160019091015550837f1d6f5e03d3f63eb58751986629a5439baee5079ff04f345becb66e23eb154e46848460405191825260208201526040908101905180910390a250505050565b6000908152600160208190526040909120015490565b600090815260016020526040902054600160a060020a031690565b610a67611101565b60008381526001602052604090819020600501908390518082805190602001908083835b60208310610aaa5780518252601f199092019160209182019101610a8b565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390208054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610b715780601f10610b4657610100808354040283529160200191610b71565b820191906000526020600020905b815481529060010190602001808311610b5457829003601f168201915b5050505050905092915050565b600080548491600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610bd757600080fd5b6102c65a03f11515610be857600080fd5b50505060405180519050600160a060020a0316141515610c0757600080fd5b6000198301831615610c1857600080fd5b60008481526001602090815260408083208684526006019091529020828051610c45929160200190611083565b5082847faa121bbeef5f32f5961a2a28966e769023910fc9479059ee3495d4c1a696efe360405160405180910390a350505050565b610c82611101565b6001600083600019166000191681526020019081526020016000206002018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610d345780601f10610d0957610100808354040283529160200191610d34565b820191906000526020600020905b815481529060010190602001808311610d1757829003601f168201915b50505050509050919050565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610d9957600080fd5b6102c65a03f11515610daa57600080fd5b50505060405180519050600160a060020a0316141515610dc957600080fd5b6000838152600160205260409020600201828051610deb929160200190611083565b50827fb7d29e911041e8d9b843369e890bcb72c9388692ba48b65ac54e7214c4c348f78360405160208082528190810183818151815260200191508051906020019080838360005b83811015610e4b578082015183820152602001610e33565b50505050905090810190601f168015610e785780820380516001836020036101000a031916815260200191505b509250505060405180910390a2505050565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610ee357600080fd5b6102c65a03f11515610ef457600080fd5b50505060405180519050600160a060020a0316141515610f1357600080fd5b6000838152600160208190526040918290200183905583907f0424b6fe0d9c3bdbece0e7879dc241bb0c22e900be8b6c168b4ee08bd9bf83bc9084905190815260200160405180910390a2505050565b600090815260016020526040902060038101546004909101549091565b600080548391600160a060020a033381169216906302571be39084906040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b1515610fd957600080fd5b6102c65a03f11515610fea57600080fd5b50505060405180519050600160a060020a031614151561100957600080fd5b60008381526001602052604090819020805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03851617905583907f52d7d861f09ab3d26239d492e8968629f95e9e318cf0b73bfddc441522a15fd290849051600160a060020a03909116815260200160405180910390a2505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106110c457805160ff19168380011785556110f1565b828001600101855582156110f1579182015b828111156110f15782518255916020019190600101906110d6565b506110fd929150611113565b5090565b60206040519081016040526000815290565b61112d91905b808211156110fd5760008155600101611119565b905600a165627a7a723058206016a807d9d5f6060e9c0d1c808e52d4ca30a4cab0140adcc6587bfc13bedf100029" reverse_registrar_abi = json.loads('[{"constant":false,"inputs":[{"name":"owner","type":"address"},{"name":"resolver","type":"address"}],"name":"claimWithResolver","outputs":[{"name":"node","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"owner","type":"address"}],"name":"claim","outputs":[{"name":"node","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"ens","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"defaultResolver","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"addr","type":"address"}],"name":"node","outputs":[{"name":"ret","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"name","type":"string"}],"name":"setName","outputs":[{"name":"node","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"ensAddr","type":"address"},{"name":"resolverAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]') reverse_registrar_bytecode = "6060604052341561000f57600080fd5b604051604080610d96833981016040528080519060200190919080519060200190919050506000826000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555081600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be37f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26001026000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b151561017a57600080fd5b6102c65a03f1151561018b57600080fd5b50505060405180519050905060008173ffffffffffffffffffffffffffffffffffffffff16141515610277578073ffffffffffffffffffffffffffffffffffffffff16631e83409a336000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001915050602060405180830381600087803b151561025a57600080fd5b6102c65a03f1151561026b57600080fd5b50505060405180519050505b505050610b0d806102896000396000f300606060405260043610610078576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630f5a54661461007d5780631e83409a146100f15780633f15457f14610146578063828eab0e1461019b578063bffbe61c146101f0578063c47f002714610245575b600080fd5b341561008857600080fd5b6100d3600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506102be565b60405180826000191660001916815260200191505060405180910390f35b34156100fc57600080fd5b610128600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190505061086e565b60405180826000191660001916815260200191505060405180910390f35b341561015157600080fd5b610159610882565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101a657600080fd5b6101ae6108a7565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101fb57600080fd5b610227600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108cd565b60405180826000191660001916815260200191505060405180910390f35b341561025057600080fd5b6102a0600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061092f565b60405180826000191660001916815260200191505060405180910390f35b60008060006102cc33610a80565b91507f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010282604051808360001916600019168152602001826000191660001916815260200192505050604051809103902092506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be3846000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b15156103c157600080fd5b6102c65a03f115156103d257600080fd5b50505060405180519050905060008473ffffffffffffffffffffffffffffffffffffffff16141580156104eb57506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630178b8bf846000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b15156104a057600080fd5b6102c65a03f115156104b157600080fd5b5050506040518051905073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614155b1561071b573073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614151561063b576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166306ab59237f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010284306040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180846000191660001916815260200183600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019350505050600060405180830381600087803b151561062357600080fd5b6102c65a03f1151561063457600080fd5b5050503090505b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16631896f70a84866040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200192505050600060405180830381600087803b151561070657600080fd5b6102c65a03f1151561071757600080fd5b5050505b8473ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16141515610863576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166306ab59237f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010284886040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180846000191660001916815260200183600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019350505050600060405180830381600087803b151561084e57600080fd5b6102c65a03f1151561085f57600080fd5b5050505b829250505092915050565b600061087b8260006102be565b9050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60007f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26001026108fc83610a80565b60405180836000191660001916815260200182600019166000191681526020019250505060405180910390209050919050565b600061095d30600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166102be565b9050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16637737221382846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180836000191660001916815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610a185780820151818401526020810190506109fd565b50505050905090810190601f168015610a455780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b1515610a6457600080fd5b6102c65a03f11515610a7557600080fd5b505050809050919050565b60007f303132333435363738396162636465660000000000000000000000000000000060285b60018103905081600f85161a815360108404935060018103905081600f85161a815360108404935080610aa6576028600020925050509190505600a165627a7a72305820a8513240f040cd9ded89ca4d0c5bda58536850e642e1d933ad64158ef4c820660029" reverse_registrar_bytecode_runtime = "606060405260043610610078576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630f5a54661461007d5780631e83409a146100f15780633f15457f14610146578063828eab0e1461019b578063bffbe61c146101f0578063c47f002714610245575b600080fd5b341561008857600080fd5b6100d3600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506102be565b60405180826000191660001916815260200191505060405180910390f35b34156100fc57600080fd5b610128600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190505061086e565b60405180826000191660001916815260200191505060405180910390f35b341561015157600080fd5b610159610882565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101a657600080fd5b6101ae6108a7565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156101fb57600080fd5b610227600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108cd565b60405180826000191660001916815260200191505060405180910390f35b341561025057600080fd5b6102a0600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061092f565b60405180826000191660001916815260200191505060405180910390f35b60008060006102cc33610a80565b91507f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010282604051808360001916600019168152602001826000191660001916815260200192505050604051809103902092506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be3846000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b15156103c157600080fd5b6102c65a03f115156103d257600080fd5b50505060405180519050905060008473ffffffffffffffffffffffffffffffffffffffff16141580156104eb57506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630178b8bf846000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b15156104a057600080fd5b6102c65a03f115156104b157600080fd5b5050506040518051905073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614155b1561071b573073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614151561063b576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166306ab59237f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010284306040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180846000191660001916815260200183600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019350505050600060405180830381600087803b151561062357600080fd5b6102c65a03f1151561063457600080fd5b5050503090505b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16631896f70a84866040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200192505050600060405180830381600087803b151561070657600080fd5b6102c65a03f1151561071757600080fd5b5050505b8473ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16141515610863576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166306ab59237f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e260010284886040518463ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180846000191660001916815260200183600019166000191681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019350505050600060405180830381600087803b151561084e57600080fd5b6102c65a03f1151561085f57600080fd5b5050505b829250505092915050565b600061087b8260006102be565b9050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60007f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26001026108fc83610a80565b60405180836000191660001916815260200182600019166000191681526020019250505060405180910390209050919050565b600061095d30600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166102be565b9050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16637737221382846040518363ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180836000191660001916815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610a185780820151818401526020810190506109fd565b50505050905090810190601f168015610a455780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b1515610a6457600080fd5b6102c65a03f11515610a7557600080fd5b505050809050919050565b60007f303132333435363738396162636465660000000000000000000000000000000060285b60018103905081600f85161a815360108404935060018103905081600f85161a815360108404935080610aa6576028600020925050509190505600a165627a7a72305820a8513240f040cd9ded89ca4d0c5bda58536850e642e1d933ad64158ef4c820660029" reverse_resolver_abi = json.loads('[{"constant":true,"inputs":[],"name":"ens","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"_name","type":"string"}],"name":"setName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"ensAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]') reverse_resolver_bytecode = "6060604052341561000f57600080fd5b6040516020806106c9833981016040528080519060200190919050506000816000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be37f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26001026000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b151561013057600080fd5b6102c65a03f1151561014157600080fd5b50505060405180519050905060008173ffffffffffffffffffffffffffffffffffffffff1614151561022d578073ffffffffffffffffffffffffffffffffffffffff16631e83409a336000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001915050602060405180830381600087803b151561021057600080fd5b6102c65a03f1151561022157600080fd5b50505060405180519050505b505061048b8061023e6000396000f300606060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633f15457f1461005c578063691f3431146100b15780637737221314610151575b600080fd5b341561006757600080fd5b61006f6101bb565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156100bc57600080fd5b6100d66004808035600019169060200190919050506101e0565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101165780820151818401526020810190506100fb565b50505050905090810190601f1680156101435780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561015c57600080fd5b6101b960048080356000191690602001909190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610290565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60016020528060005260406000206000915090508054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102885780601f1061025d57610100808354040283529160200191610288565b820191906000526020600020905b81548152906001019060200180831161026b57829003601f168201915b505050505081565b816000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be3826000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b151561033157600080fd5b6102c65a03f1151561034257600080fd5b5050506040518051905073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561038557600080fd5b8160016000856000191660001916815260200190815260200160002090805190602001906103b49291906103ba565b50505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106103fb57805160ff1916838001178555610429565b82800160010185558215610429579182015b8281111561042857825182559160200191906001019061040d565b5b509050610436919061043a565b5090565b61045c91905b80821115610458576000816000905550600101610440565b5090565b905600a165627a7a72305820f4c4cb4d191f31a62c4de12f7aecf9b258ba17f3a6ee294191171f7d30c04ab00029" reverse_resolver_bytecode_runtime = "606060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633f15457f1461005c578063691f3431146100b15780637737221314610151575b600080fd5b341561006757600080fd5b61006f6101bb565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156100bc57600080fd5b6100d66004808035600019169060200190919050506101e0565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101165780820151818401526020810190506100fb565b50505050905090810190601f1680156101435780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561015c57600080fd5b6101b960048080356000191690602001909190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610290565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60016020528060005260406000206000915090508054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102885780601f1061025d57610100808354040283529160200191610288565b820191906000526020600020905b81548152906001019060200180831161026b57829003601f168201915b505050505081565b816000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166302571be3826000604051602001526040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808260001916600019168152602001915050602060405180830381600087803b151561033157600080fd5b6102c65a03f1151561034257600080fd5b5050506040518051905073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561038557600080fd5b8160016000856000191660001916815260200190815260200160002090805190602001906103b49291906103ba565b50505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106103fb57805160ff1916838001178555610429565b82800160010185558215610429579182015b8281111561042857825182559160200191906001019061040d565b5b509050610436919061043a565b5090565b61045c91905b80821115610458576000816000905550600101610440565b5090565b905600a165627a7a72305820f4c4cb4d191f31a62c4de12f7aecf9b258ba17f3a6ee294191171f7d30c04ab00029"
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/contract_data.py
contract_data.py
from eth_utils import ( is_binary_address, is_checksum_address, to_checksum_address, ) from ens import abis from ens.constants import ( EMPTY_ADDR_HEX, REVERSE_REGISTRAR_DOMAIN, ) from ens.exceptions import ( AddressMismatch, UnauthorizedError, UnownedName, ) from ens.utils import ( address_in, address_to_reverse_domain, default, dict_copy, init_web3, is_none_or_zero_address, is_valid_name, label_to_hash, normal_name_to_hash, normalize_name, raw_name_to_hash, ) ENS_MAINNET_ADDR = '0x314159265dD8dbb310642f98f50C066173C1259b' class ENS: """ Quick access to common Ethereum Name Service functions, like getting the address for a name. Unless otherwise specified, all addresses are assumed to be a `str` in `checksum format <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md>`_, like: ``"0x314159265dD8dbb310642f98f50C066173C1259b"`` """ labelhash = staticmethod(label_to_hash) namehash = staticmethod(raw_name_to_hash) nameprep = staticmethod(normalize_name) is_valid_name = staticmethod(is_valid_name) reverse_domain = staticmethod(address_to_reverse_domain) def __init__(self, provider=default, addr=None): """ :param provider: a single provider used to connect to Ethereum :type provider: instance of `web3.providers.base.BaseProvider` :param hex-string addr: the address of the ENS registry on-chain. If not provided, ENS.py will default to the mainnet ENS registry address. """ self.web3 = init_web3(provider) ens_addr = addr if addr else ENS_MAINNET_ADDR self.ens = self.web3.eth.contract(abi=abis.ENS, address=ens_addr) self._resolverContract = self.web3.eth.contract(abi=abis.RESOLVER) @classmethod def fromWeb3(cls, web3, addr=None): """ Generate an ENS instance with web3 :param `web3.Web3` web3: to infer connection information :param hex-string addr: the address of the ENS registry on-chain. If not provided, ENS.py will default to the mainnet ENS registry address. """ return cls(web3.manager.provider, addr=addr) def address(self, name): """ Look up the Ethereum address that `name` currently points to. :param str name: an ENS name to look up :raises InvalidName: if `name` has invalid syntax """ return self.resolve(name, 'addr') def name(self, address): """ Look up the name that the address points to, using a reverse lookup. Reverse lookup is opt-in for name owners. :param address: :type address: hex-string """ reversed_domain = address_to_reverse_domain(address) return self.resolve(reversed_domain, get='name') @dict_copy def setup_address(self, name, address=default, transact={}): """ Set up the name to point to the supplied address. The sender of the transaction must own the name, or its parent name. Example: If the caller owns ``parentname.eth`` with no subdomains and calls this method with ``sub.parentname.eth``, then ``sub`` will be created as part of this call. :param str name: ENS name to set up :param str address: name will point to this address, in checksum format. If ``None``, erase the record. If not specified, name will point to the owner's address. :param dict transact: the transaction configuration, like in :meth:`~web3.eth.Eth.sendTransaction` :raises InvalidName: if ``name`` has invalid syntax :raises UnauthorizedError: if ``'from'`` in `transact` does not own `name` """ owner = self.setup_owner(name, transact=transact) self._assert_control(owner, name) if is_none_or_zero_address(address): address = None elif address is default: address = owner elif is_binary_address(address): address = to_checksum_address(address) elif not is_checksum_address(address): raise ValueError("You must supply the address in checksum format") if self.address(name) == address: return None if address is None: address = EMPTY_ADDR_HEX transact['from'] = owner resolver = self._set_resolver(name, transact=transact) return resolver.functions.setAddr(raw_name_to_hash(name), address).transact(transact) @dict_copy def setup_name(self, name, address=None, transact={}): """ Set up the address for reverse lookup, aka "caller ID". After successful setup, the method :meth:`~ens.main.ENS.name` will return `name` when supplied with `address`. :param str name: ENS name that address will point to :param str address: to set up, in checksum format :param dict transact: the transaction configuration, like in :meth:`~web3.eth.sendTransaction` :raises AddressMismatch: if the name does not already point to the address :raises InvalidName: if `name` has invalid syntax :raises UnauthorizedError: if ``'from'`` in `transact` does not own `name` :raises UnownedName: if no one owns `name` """ if not name: self._assert_control(address, 'the reverse record') return self._setup_reverse(None, address, transact=transact) else: resolved = self.address(name) if is_none_or_zero_address(address): address = resolved elif resolved and address != resolved and resolved != EMPTY_ADDR_HEX: raise AddressMismatch( "Could not set address %r to point to name, because the name resolves to %r. " "To change the name for an existing address, call setup_address() first." % ( address, resolved ) ) if is_none_or_zero_address(address): address = self.owner(name) if is_none_or_zero_address(address): raise UnownedName("claim subdomain using setup_address() first") if is_binary_address(address): address = to_checksum_address(address) if not is_checksum_address(address): raise ValueError("You must supply the address in checksum format") self._assert_control(address, name) if not resolved: self.setup_address(name, address, transact=transact) return self._setup_reverse(name, address, transact=transact) def resolve(self, name, get='addr'): normal_name = normalize_name(name) resolver = self.resolver(normal_name) if resolver: lookup_function = getattr(resolver.functions, get) namehash = normal_name_to_hash(normal_name) address = lookup_function(namehash).call() if is_none_or_zero_address(address): return None return lookup_function(namehash).call() else: return None def resolver(self, normal_name): resolver_addr = self.ens.caller.resolver(normal_name_to_hash(normal_name)) if is_none_or_zero_address(resolver_addr): return None return self._resolverContract(address=resolver_addr) def reverser(self, target_address): reversed_domain = address_to_reverse_domain(target_address) return self.resolver(reversed_domain) def owner(self, name): """ Get the owner of a name. Note that this may be different from the deed holder in the '.eth' registrar. Learn more about the difference between deed and name ownership in the ENS `Managing Ownership docs <http://docs.ens.domains/en/latest/userguide.html#managing-ownership>`_ :param str name: ENS name to look up :return: owner address :rtype: str """ node = raw_name_to_hash(name) return self.ens.caller.owner(node) @dict_copy def setup_owner(self, name, new_owner=default, transact={}): """ Set the owner of the supplied name to `new_owner`. For typical scenarios, you'll never need to call this method directly, simply call :meth:`setup_name` or :meth:`setup_address`. This method does *not* set up the name to point to an address. If `new_owner` is not supplied, then this will assume you want the same owner as the parent domain. If the caller owns ``parentname.eth`` with no subdomains and calls this method with ``sub.parentname.eth``, then ``sub`` will be created as part of this call. :param str name: ENS name to set up :param new_owner: account that will own `name`. If ``None``, set owner to empty addr. If not specified, name will point to the parent domain owner's address. :param dict transact: the transaction configuration, like in :meth:`~web3.eth.Eth.sendTransaction` :raises InvalidName: if `name` has invalid syntax :raises UnauthorizedError: if ``'from'`` in `transact` does not own `name` :returns: the new owner's address """ (super_owner, unowned, owned) = self._first_owner(name) if new_owner is default: new_owner = super_owner elif not new_owner: new_owner = EMPTY_ADDR_HEX else: new_owner = to_checksum_address(new_owner) current_owner = self.owner(name) if new_owner == EMPTY_ADDR_HEX and not current_owner: return None elif current_owner == new_owner: return current_owner else: self._assert_control(super_owner, name, owned) self._claim_ownership(new_owner, unowned, owned, super_owner, transact=transact) return new_owner def _assert_control(self, account, name, parent_owned=None): if not address_in(account, self.web3.eth.accounts): raise UnauthorizedError( "in order to modify %r, you must control account %r, which owns %r" % ( name, account, parent_owned or name ) ) def _first_owner(self, name): """ Takes a name, and returns the owner of the deepest subdomain that has an owner :returns: (owner or None, list(unowned_subdomain_labels), first_owned_domain) """ owner = None unowned = [] pieces = normalize_name(name).split('.') while pieces and is_none_or_zero_address(owner): name = '.'.join(pieces) owner = self.owner(name) if is_none_or_zero_address(owner): unowned.append(pieces.pop(0)) return (owner, unowned, name) @dict_copy def _claim_ownership(self, owner, unowned, owned, old_owner=None, transact={}): transact['from'] = old_owner or owner for label in reversed(unowned): self.ens.functions.setSubnodeOwner( raw_name_to_hash(owned), label_to_hash(label), owner ).transact(transact) owned = "%s.%s" % (label, owned) @dict_copy def _set_resolver(self, name, resolver_addr=None, transact={}): if is_none_or_zero_address(resolver_addr): resolver_addr = self.address('resolver.eth') namehash = raw_name_to_hash(name) if self.ens.caller.resolver(namehash) != resolver_addr: self.ens.functions.setResolver( namehash, resolver_addr ).transact(transact) return self._resolverContract(address=resolver_addr) @dict_copy def _setup_reverse(self, name, address, transact={}): if name: name = normalize_name(name) else: name = '' transact['from'] = address return self._reverse_registrar().functions.setName(name).transact(transact) def _reverse_registrar(self): addr = self.ens.caller.owner(normal_name_to_hash(REVERSE_REGISTRAR_DOMAIN)) return self.web3.eth.contract(address=addr, abi=abis.REVERSE_REGISTRAR)
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/main.py
main.py
import copy import datetime import functools from eth_utils import ( is_same_address, remove_0x_prefix, to_normalized_address, ) import idna from ens.constants import ( ACCEPTABLE_STALE_HOURS, AUCTION_START_GAS_CONSTANT, AUCTION_START_GAS_MARGINAL, EMPTY_SHA3_BYTES, MIN_ETH_LABEL_LENGTH, REVERSE_REGISTRAR_DOMAIN, ) from ens.exceptions import ( InvalidLabel, InvalidName, ) default = object() def Web3(): from web3 import Web3 return Web3 def dict_copy(func): "copy dict keyword args, to avoid modifying caller's copy" @functools.wraps(func) def wrapper(*args, **kwargs): copied_kwargs = copy.deepcopy(kwargs) return func(*args, **copied_kwargs) return wrapper def ensure_hex(data): if not isinstance(data, str): return Web3().toHex(data) return data def init_web3(providers=default): from web3 import Web3 if providers is default: w3 = Web3(ens=None) else: w3 = Web3(providers, ens=None) return customize_web3(w3) def customize_web3(w3): from web3.middleware import make_stalecheck_middleware w3.middleware_onion.remove('name_to_address') w3.middleware_onion.add( make_stalecheck_middleware(ACCEPTABLE_STALE_HOURS * 3600), name='stalecheck', ) return w3 def normalize_name(name): """ Clean the fully qualified name, as defined in ENS `EIP-137 <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_ This does *not* enforce whether ``name`` is a label or fully qualified domain. :param str name: the dot-separated ENS name :raises InvalidName: if ``name`` has invalid syntax """ if not name: return name elif isinstance(name, (bytes, bytearray)): name = name.decode('utf-8') try: return idna.decode(name, uts46=True, std3_rules=True) except idna.IDNAError as exc: raise InvalidName("%s is an invalid name, because %s" % (name, exc)) from exc def is_valid_name(name): """ Validate whether the fully qualified name is valid, as defined in ENS `EIP-137 <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_ :param str name: the dot-separated ENS name :returns: True if ``name`` is set, and :meth:`~ens.main.ENS.nameprep` will not raise InvalidName """ if not name: return False try: normalize_name(name) return True except InvalidName: return False def name_to_label(name, registrar): name = normalize_name(name) if '.' not in name: label = name else: name_pieces = name.split('.') registrar_pieces = registrar.split('.') if len(name_pieces) != len(registrar_pieces) + 1: raise ValueError( "You must specify a label, like 'tickets' " "or a fully-qualified name, like 'tickets.%s'" % registrar ) label, *label_registrar = name_pieces if label_registrar != registrar_pieces: raise ValueError("This interface only manages names under .%s " % registrar) return label def dot_eth_label(name): """ Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex' If name is already a label, this should be a noop, except for converting to a string and validating the name syntax. """ label = name_to_label(name, registrar='eth') if len(label) < MIN_ETH_LABEL_LENGTH: raise InvalidLabel('name %r is too short' % label) else: return label def to_utc_datetime(timestamp): if timestamp: return datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc) else: return None def sha3_text(val): if isinstance(val, str): val = val.encode('utf-8') return Web3().keccak(val) def label_to_hash(label): label = normalize_name(label) if '.' in label: raise ValueError("Cannot generate hash for label %r with a '.'" % label) return Web3().keccak(text=label) def normal_name_to_hash(name): node = EMPTY_SHA3_BYTES if name: labels = name.split(".") for label in reversed(labels): labelhash = label_to_hash(label) assert isinstance(labelhash, bytes) assert isinstance(node, bytes) node = Web3().keccak(node + labelhash) return node def raw_name_to_hash(name): """ Generate the namehash. This is also known as the ``node`` in ENS contracts. In normal operation, generating the namehash is handled behind the scenes. For advanced usage, it is a helpful utility. This normalizes the name with `nameprep <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md#name-syntax>`_ before hashing. :param str name: ENS name to hash :return: the namehash :rtype: bytes :raises InvalidName: if ``name`` has invalid syntax """ normalized_name = normalize_name(name) return normal_name_to_hash(normalized_name) def address_in(address, addresses): return any(is_same_address(address, item) for item in addresses) def address_to_reverse_domain(address): lower_unprefixed_address = remove_0x_prefix(to_normalized_address(address)) return lower_unprefixed_address + '.' + REVERSE_REGISTRAR_DOMAIN def estimate_auction_start_gas(labels): return AUCTION_START_GAS_CONSTANT + AUCTION_START_GAS_MARGINAL * len(labels) def assert_signer_in_modifier_kwargs(modifier_kwargs): ERR_MSG = "You must specify the sending account" assert len(modifier_kwargs) == 1, ERR_MSG _modifier_type, modifier_dict = dict(modifier_kwargs).popitem() if 'from' not in modifier_dict: raise TypeError(ERR_MSG) return modifier_dict['from'] def is_none_or_zero_address(addr): return not addr or addr == '0x' + '00' * 20
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/utils.py
utils.py
ENS = [ { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "resolver", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "label", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "setSubnodeOwner", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "ttl", "type": "uint64" } ], "name": "setTTL", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "ttl", "outputs": [ { "name": "", "type": "uint64" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "resolver", "type": "address" } ], "name": "setResolver", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "setOwner", "outputs": [], "payable": False, "type": "function" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "owner", "type": "address" } ], "name": "Transfer", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": True, "name": "label", "type": "bytes32" }, { "indexed": False, "name": "owner", "type": "address" } ], "name": "NewOwner", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "resolver", "type": "address" } ], "name": "NewResolver", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "ttl", "type": "uint64" } ], "name": "NewTTL", "type": "event" } ] AUCTION_REGISTRAR = [ { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "releaseDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "getAllowedTime", "outputs": [ { "name": "timestamp", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "unhashedName", "type": "string" } ], "name": "invalidateName", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "hash", "type": "bytes32" }, { "name": "owner", "type": "address" }, { "name": "value", "type": "uint256" }, { "name": "salt", "type": "bytes32" } ], "name": "shaBid", "outputs": [ { "name": "sealedBid", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "bidder", "type": "address" }, { "name": "seal", "type": "bytes32" } ], "name": "cancelBid", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "entries", "outputs": [ { "name": "", "type": "uint8" }, { "name": "", "type": "address" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "ens", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "_value", "type": "uint256" }, { "name": "_salt", "type": "bytes32" } ], "name": "unsealBid", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "transferRegistrars", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "", "type": "address" }, { "name": "", "type": "bytes32" } ], "name": "sealedBids", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "state", "outputs": [ { "name": "", "type": "uint8" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "newOwner", "type": "address" } ], "name": "transfer", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "_timestamp", "type": "uint256" } ], "name": "isAllowed", "outputs": [ { "name": "allowed", "type": "bool" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "finalizeAuction", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "registryStarted", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "launchLength", "outputs": [ { "name": "", "type": "uint32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "sealedBid", "type": "bytes32" } ], "name": "newBid", "outputs": [], "payable": True, "type": "function" }, { "constant": False, "inputs": [ { "name": "labels", "type": "bytes32[]" } ], "name": "eraseNode", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hashes", "type": "bytes32[]" } ], "name": "startAuctions", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "hash", "type": "bytes32" }, { "name": "deed", "type": "address" }, { "name": "registrationDate", "type": "uint256" } ], "name": "acceptRegistrarTransfer", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "startAuction", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "rootNode", "outputs": [ { "name": "", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "hashes", "type": "bytes32[]" }, { "name": "sealedBid", "type": "bytes32" } ], "name": "startAuctionsAndBid", "outputs": [], "payable": True, "type": "function" }, { "inputs": [ { "name": "_ens", "type": "address" }, { "name": "_rootNode", "type": "bytes32" }, { "name": "_startDate", "type": "uint256" } ], "payable": False, "type": "constructor" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "AuctionStarted", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "bidder", "type": "address" }, { "indexed": False, "name": "deposit", "type": "uint256" } ], "name": "NewBid", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "owner", "type": "address" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "status", "type": "uint8" } ], "name": "BidRevealed", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "owner", "type": "address" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "HashRegistered", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": False, "name": "value", "type": "uint256" } ], "name": "HashReleased", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "name", "type": "string" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "HashInvalidated", "type": "event" } ] DEED = [ { "constant": True, "inputs": [], "name": "creationDate", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [], "name": "destroyDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newOwner", "type": "address" } ], "name": "setOwner", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "registrar", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "refundRatio", "type": "uint256" } ], "name": "closeDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newRegistrar", "type": "address" } ], "name": "setRegistrar", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newValue", "type": "uint256" } ], "name": "setBalance", "outputs": [], "payable": True, "type": "function" }, { "inputs": [], "type": "constructor" }, { "payable": True, "type": "fallback" }, { "anonymous": False, "inputs": [ { "indexed": False, "name": "newOwner", "type": "address" } ], "name": "OwnerChanged", "type": "event" }, { "anonymous": False, "inputs": [], "name": "DeedClosed", "type": "event" } ] FIFS_REGISTRAR = [ { "constant": True, "inputs": [], "name": "ens", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "", "type": "bytes32" } ], "name": "expiryTimes", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "subnode", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "register", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "rootNode", "outputs": [ { "name": "", "type": "bytes32" } ], "payable": False, "type": "function" }, { "inputs": [ { "name": "ensAddr", "type": "address" }, { "name": "node", "type": "bytes32" } ], "type": "constructor" } ] RESOLVER = [ { "constant": True, "inputs": [ { "name": "interfaceID", "type": "bytes4" } ], "name": "supportsInterface", "outputs": [ { "name": "", "type": "bool" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "contentTypes", "type": "uint256" } ], "name": "ABI", "outputs": [ { "name": "contentType", "type": "uint256" }, { "name": "data", "type": "bytes" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "x", "type": "bytes32" }, { "name": "y", "type": "bytes32" } ], "name": "setPubkey", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "content", "outputs": [ { "name": "ret", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "addr", "outputs": [ { "name": "ret", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "contentType", "type": "uint256" }, { "name": "data", "type": "bytes" } ], "name": "setABI", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "name", "outputs": [ { "name": "ret", "type": "string" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "name", "type": "string" } ], "name": "setName", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "hash", "type": "bytes32" } ], "name": "setContent", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "pubkey", "outputs": [ { "name": "x", "type": "bytes32" }, { "name": "y", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "addr", "type": "address" } ], "name": "setAddr", "outputs": [], "payable": False, "type": "function" }, { "inputs": [ { "name": "ensAddr", "type": "address" } ], "payable": False, "type": "constructor" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "a", "type": "address" } ], "name": "AddrChanged", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "hash", "type": "bytes32" } ], "name": "ContentChanged", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "name", "type": "string" } ], "name": "NameChanged", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": True, "name": "contentType", "type": "uint256" } ], "name": "ABIChanged", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "node", "type": "bytes32" }, { "indexed": False, "name": "x", "type": "bytes32" }, { "indexed": False, "name": "y", "type": "bytes32" } ], "name": "PubkeyChanged", "type": "event" } ] REVERSE_REGISTRAR = [ { "constant": False, "inputs": [ { "name": "owner", "type": "address" }, { "name": "resolver", "type": "address" } ], "name": "claimWithResolver", "outputs": [ { "name": "node", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "owner", "type": "address" } ], "name": "claim", "outputs": [ { "name": "node", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "ens", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "defaultResolver", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "addr", "type": "address" } ], "name": "node", "outputs": [ { "name": "ret", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "name", "type": "string" } ], "name": "setName", "outputs": [ { "name": "node", "type": "bytes32" } ], "payable": False, "type": "function" }, { "inputs": [ { "name": "ensAddr", "type": "address" }, { "name": "resolverAddr", "type": "address" } ], "payable": False, "type": "constructor" } ]
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/ens/abis.py
abis.py
from eth_account import ( Account, ) from eth_utils import ( apply_to_return_value, is_checksum_address, is_string, ) from hexbytes import ( HexBytes, ) from web3._utils.blocks import ( select_method_for_block_identifier, ) from web3._utils.decorators import ( deprecated_for, ) from web3._utils.empty import ( empty, ) from web3._utils.encoding import ( to_hex, ) from web3._utils.filters import ( BlockFilter, LogFilter, TransactionFilter, ) from web3._utils.threads import ( Timeout, ) from web3._utils.toolz import ( assoc, merge, ) from web3._utils.transactions import ( assert_valid_transaction_params, extract_valid_transaction_params, get_buffered_gas_estimate, get_required_transaction, replace_transaction, wait_for_transaction_receipt, ) from web3.contract import ( Contract, ) from web3.exceptions import ( TimeExhausted, ) from web3.iban import ( Iban, ) from web3.module import ( Module, ) class Eth(Module): account = Account() defaultAccount = empty defaultBlock = "latest" defaultContractFactory = Contract iban = Iban gasPriceStrategy = None @deprecated_for("doing nothing at all") def enable_unaudited_features(self): pass def namereg(self): raise NotImplementedError() def icapNamereg(self): raise NotImplementedError() @property def protocolVersion(self): return self.web3.manager.request_blocking("eth_protocolVersion", []) @property def syncing(self): return self.web3.manager.request_blocking("eth_syncing", []) @property def coinbase(self): return self.web3.manager.request_blocking("eth_coinbase", []) @property def mining(self): return self.web3.manager.request_blocking("eth_mining", []) @property def hashrate(self): return self.web3.manager.request_blocking("eth_hashrate", []) @property def gasPrice(self): return self.web3.manager.request_blocking("eth_gasPrice", []) @property def accounts(self): return self.web3.manager.request_blocking("eth_accounts", []) @property def blockNumber(self): return self.web3.manager.request_blocking("eth_blockNumber", []) def getBalance(self, account, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_getBalance", [account, block_identifier], ) def getStorageAt(self, account, position, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_getStorageAt", [account, position, block_identifier] ) def getCode(self, account, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_getCode", [account, block_identifier], ) def getBlock(self, block_identifier, full_transactions=False): """ `eth_getBlockByHash` `eth_getBlockByNumber` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getBlockByNumber', if_hash='eth_getBlockByHash', if_number='eth_getBlockByNumber', ) return self.web3.manager.request_blocking( method, [block_identifier, full_transactions], ) def getBlockTransactionCount(self, block_identifier): """ `eth_getBlockTransactionCountByHash` `eth_getBlockTransactionCountByNumber` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getBlockTransactionCountByNumber', if_hash='eth_getBlockTransactionCountByHash', if_number='eth_getBlockTransactionCountByNumber', ) return self.web3.manager.request_blocking( method, [block_identifier], ) def getUncleCount(self, block_identifier): """ `eth_getUncleCountByBlockHash` `eth_getUncleCountByBlockNumber` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getUncleCountByBlockNumber', if_hash='eth_getUncleCountByBlockHash', if_number='eth_getUncleCountByBlockNumber', ) return self.web3.manager.request_blocking( method, [block_identifier], ) def getUncleByBlock(self, block_identifier, uncle_index): """ `eth_getUncleByBlockHashAndIndex` `eth_getUncleByBlockNumberAndIndex` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getUncleByBlockNumberAndIndex', if_hash='eth_getUncleByBlockHashAndIndex', if_number='eth_getUncleByBlockNumberAndIndex', ) return self.web3.manager.request_blocking( method, [block_identifier, uncle_index], ) def getTransaction(self, transaction_hash): return self.web3.manager.request_blocking( "eth_getTransactionByHash", [transaction_hash], ) @deprecated_for("w3.eth.getTransactionByBlock") def getTransactionFromBlock(self, block_identifier, transaction_index): """ Alias for the method getTransactionByBlock Depreceated to maintain naming consistency with the json-rpc API """ return self.getTransactionByBlock(block_identifier, transaction_index) def getTransactionByBlock(self, block_identifier, transaction_index): """ `eth_getTransactionByBlockHashAndIndex` `eth_getTransactionByBlockNumberAndIndex` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getTransactionByBlockNumberAndIndex', if_hash='eth_getTransactionByBlockHashAndIndex', if_number='eth_getTransactionByBlockNumberAndIndex', ) return self.web3.manager.request_blocking( method, [block_identifier, transaction_index], ) def waitForTransactionReceipt(self, transaction_hash, timeout=120): try: return wait_for_transaction_receipt(self.web3, transaction_hash, timeout) except Timeout: raise TimeExhausted( "Transaction {} is not in the chain, after {} seconds".format( transaction_hash, timeout, ) ) def getTransactionReceipt(self, transaction_hash): return self.web3.manager.request_blocking( "eth_getTransactionReceipt", [transaction_hash], ) def getTransactionCount(self, account, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_getTransactionCount", [ account, block_identifier, ], ) def replaceTransaction(self, transaction_hash, new_transaction): current_transaction = get_required_transaction(self.web3, transaction_hash) return replace_transaction(self.web3, current_transaction, new_transaction) def modifyTransaction(self, transaction_hash, **transaction_params): assert_valid_transaction_params(transaction_params) current_transaction = get_required_transaction(self.web3, transaction_hash) current_transaction_params = extract_valid_transaction_params(current_transaction) new_transaction = merge(current_transaction_params, transaction_params) return replace_transaction(self.web3, current_transaction, new_transaction) def sendTransaction(self, transaction): # TODO: move to middleware if 'from' not in transaction and is_checksum_address(self.defaultAccount): transaction = assoc(transaction, 'from', self.defaultAccount) # TODO: move gas estimation in middleware if 'gas' not in transaction: transaction = assoc( transaction, 'gas', get_buffered_gas_estimate(self.web3, transaction), ) return self.web3.manager.request_blocking( "eth_sendTransaction", [transaction], ) def sendRawTransaction(self, raw_transaction): return self.web3.manager.request_blocking( "eth_sendRawTransaction", [raw_transaction], ) def sign(self, account, data=None, hexstr=None, text=None): message_hex = to_hex(data, hexstr=hexstr, text=text) return self.web3.manager.request_blocking( "eth_sign", [account, message_hex], ) @apply_to_return_value(HexBytes) def call(self, transaction, block_identifier=None): # TODO: move to middleware if 'from' not in transaction and is_checksum_address(self.defaultAccount): transaction = assoc(transaction, 'from', self.defaultAccount) # TODO: move to middleware if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "eth_call", [transaction, block_identifier], ) def estimateGas(self, transaction, block_identifier=None): # TODO: move to middleware if 'from' not in transaction and is_checksum_address(self.defaultAccount): transaction = assoc(transaction, 'from', self.defaultAccount) if block_identifier is None: params = [transaction] else: params = [transaction, block_identifier] return self.web3.manager.request_blocking( "eth_estimateGas", params, ) def filter(self, filter_params=None, filter_id=None): if filter_id and filter_params: raise TypeError( "Ambiguous invocation: provide either a `filter_params` or a `filter_id` argument. " "Both were supplied." ) if is_string(filter_params): if filter_params == "latest": filter_id = self.web3.manager.request_blocking( "eth_newBlockFilter", [], ) return BlockFilter(self.web3, filter_id) elif filter_params == "pending": filter_id = self.web3.manager.request_blocking( "eth_newPendingTransactionFilter", [], ) return TransactionFilter(self.web3, filter_id) else: raise ValueError( "The filter API only accepts the values of `pending` or " "`latest` for string based filters" ) elif isinstance(filter_params, dict): _filter_id = self.web3.manager.request_blocking( "eth_newFilter", [filter_params], ) return LogFilter(self.web3, _filter_id) elif filter_id and not filter_params: return LogFilter(self.web3, filter_id) else: raise TypeError("Must provide either filter_params as a string or " "a valid filter object, or a filter_id as a string " "or hex.") def getFilterChanges(self, filter_id): return self.web3.manager.request_blocking( "eth_getFilterChanges", [filter_id], ) def getFilterLogs(self, filter_id): return self.web3.manager.request_blocking( "eth_getFilterLogs", [filter_id], ) def getLogs(self, filter_params): return self.web3.manager.request_blocking( "eth_getLogs", [filter_params], ) def uninstallFilter(self, filter_id): return self.web3.manager.request_blocking( "eth_uninstallFilter", [filter_id], ) def contract(self, address=None, **kwargs): ContractFactoryClass = kwargs.pop('ContractFactoryClass', self.defaultContractFactory) ContractFactory = ContractFactoryClass.factory(self.web3, **kwargs) if address: return ContractFactory(address) else: return ContractFactory def setContractFactory(self, contractFactory): self.defaultContractFactory = contractFactory def getCompilers(self): return self.web3.manager.request_blocking("eth_getCompilers", []) def getWork(self): return self.web3.manager.request_blocking("eth_getWork", []) def generateGasPrice(self, transaction_params=None): if self.gasPriceStrategy: return self.gasPriceStrategy(self.web3, transaction_params) def setGasPriceStrategy(self, gas_price_strategy): self.gasPriceStrategy = gas_price_strategy
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/eth.py
eth.py
from eth_utils import ( is_checksum_address, ) from web3._utils.toolz import ( assoc, ) from web3.module import ( Module, ) class Parity(Module): """ https://paritytech.github.io/wiki/JSONRPC-parity-module """ defaultBlock = "latest" def enode(self): return self.web3.manager.request_blocking( "parity_enode", [], ) def listStorageKeys(self, address, quantity, hash_, block_identifier=None): if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "parity_listStorageKeys", [address, quantity, hash_, block_identifier], ) def netPeers(self): return self.web3.manager.request_blocking( "parity_netPeers", [], ) def traceReplayTransaction(self, transaction_hash, mode=['trace']): return self.web3.manager.request_blocking( "trace_replayTransaction", [transaction_hash, mode], ) def traceReplayBlockTransactions(self, block_identifier, mode=['trace']): return self.web3.manager.request_blocking( "trace_replayBlockTransactions", [block_identifier, mode] ) def traceBlock(self, block_identifier): return self.web3.manager.request_blocking( "trace_block", [block_identifier] ) def traceFilter(self, params): return self.web3.manager.request_blocking( "trace_filter", [params] ) def traceTransaction(self, transaction_hash): return self.web3.manager.request_blocking( "trace_transaction", [transaction_hash] ) def traceCall(self, transaction, mode=['trace'], block_identifier=None): # TODO: move to middleware if 'from' not in transaction and is_checksum_address(self.defaultAccount): transaction = assoc(transaction, 'from', self.defaultAccount) # TODO: move to middleware if block_identifier is None: block_identifier = self.defaultBlock return self.web3.manager.request_blocking( "trace_call", [transaction, mode, block_identifier], ) def traceRawTransaction(self, raw_transaction, mode=['trace']): return self.web3.manager.request_blocking( "trace_rawTransaction", [raw_transaction, mode], )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/parity.py
parity.py
import copy import itertools from eth_abi import ( decode_abi, ) from eth_abi.exceptions import ( DecodingError, ) from eth_utils import ( add_0x_prefix, encode_hex, function_abi_to_4byte_selector, is_list_like, is_text, to_tuple, ) from hexbytes import ( HexBytes, ) from web3._utils.abi import ( abi_to_signature, check_if_arguments_can_be_encoded, fallback_func_abi_exists, filter_by_type, get_abi_output_types, get_constructor_abi, is_array_type, map_abi_data, merge_args_and_kwargs, ) from web3._utils.blocks import ( is_hex_encoded_block_hash, ) from web3._utils.contracts import ( encode_abi, find_matching_event_abi, find_matching_fn_abi, get_function_info, prepare_transaction, ) from web3._utils.datatypes import ( PropertyCheckingFactory, ) from web3._utils.decorators import ( combomethod, deprecated_for, ) from web3._utils.empty import ( empty, ) from web3._utils.encoding import ( to_4byte_hex, to_hex, ) from web3._utils.events import ( EventFilterBuilder, get_event_data, is_dynamic_sized_type, ) from web3._utils.filters import ( construct_event_filter_params, ) from web3._utils.function_identifiers import ( FallbackFn, ) from web3._utils.normalizers import ( BASE_RETURN_NORMALIZERS, normalize_abi, normalize_address, normalize_bytecode, ) from web3._utils.toolz import ( compose, partial, ) from web3._utils.transactions import ( fill_transaction_defaults, ) from web3.exceptions import ( BadFunctionCallOutput, BlockNumberOutofRange, FallbackNotFound, MismatchedABI, NoABIEventsFound, NoABIFound, NoABIFunctionsFound, ) DEPRECATED_SIGNATURE_MESSAGE = ( "The constructor signature for the `Contract` object has changed. " "Please update your code to reflect the updated function signature: " "'Contract(address)'. To construct contract classes use the " "'Contract.factory(...)' class method." ) ACCEPTABLE_EMPTY_STRINGS = ["0x", b"0x", "", b""] class ContractFunctions: """Class containing contract function objects """ def __init__(self, abi, web3, address=None): if abi: self.abi = abi self._functions = filter_by_type('function', self.abi) for func in self._functions: setattr( self, func['name'], ContractFunction.factory( func['name'], web3=web3, contract_abi=self.abi, address=address, function_identifier=func['name'])) def __iter__(self): if not hasattr(self, '_functions') or not self._functions: return for func in self._functions: yield func['name'] def __getattr__(self, function_name): if '_functions' not in self.__dict__: raise NoABIFunctionsFound( "The abi for this contract contains no function definitions. ", "Are you sure you provided the correct contract abi?" ) elif function_name not in self.__dict__['_functions']: raise MismatchedABI( "The function '{}' was not found in this contract's abi. ".format(function_name), "Are you sure you provided the correct contract abi?" ) else: return super().__getattribute__(function_name) def __getitem__(self, function_name): return getattr(self, function_name) class ContractEvents: """Class containing contract event objects This is available via: .. code-block:: python >>> mycontract.events <web3.contract.ContractEvents object at 0x108afde10> To get list of all supported events in the contract ABI. This allows you to iterate over :class:`ContractEvent` proxy classes. .. code-block:: python >>> for e in mycontract.events: print(e) <class 'web3._utils.datatypes.LogAnonymous'> ... """ def __init__(self, abi, web3, address=None): if abi: self.abi = abi self._events = filter_by_type('event', self.abi) for event in self._events: setattr( self, event['name'], ContractEvent.factory( event['name'], web3=web3, contract_abi=self.abi, address=address, event_name=event['name'])) def __getattr__(self, event_name): if '_events' not in self.__dict__: raise NoABIEventsFound( "The abi for this contract contains no event definitions. ", "Are you sure you provided the correct contract abi?" ) elif event_name not in self.__dict__['_events']: raise MismatchedABI( "The event '{}' was not found in this contract's abi. ".format(event_name), "Are you sure you provided the correct contract abi?" ) else: return super().__getattribute__(event_name) def __getitem__(self, event_name): return getattr(self, event_name) def __iter__(self): """Iterate over supported :return: Iterable of :class:`ContractEvent` """ for event in self._events: yield self[event['name']] class Contract: """Base class for Contract proxy classes. First you need to create your Contract classes using :meth:`web3.eth.Eth.contract` that takes compiled Solidity contract ABI definitions as input. The created class object will be a subclass of this base class. After you have your Contract proxy class created you can interact with smart contracts * Create a Contract proxy object for an existing deployed smart contract by its address using :meth:`__init__` * Deploy a new smart contract using :py:meth:`Contract.deploy` """ # set during class construction web3 = None # instance level properties address = None # class properties (overridable at instance level) abi = None asm = None ast = None bytecode = None bytecode_runtime = None clone_bin = None functions = None caller = None #: Instance of :class:`ContractEvents` presenting available Event ABIs events = None dev_doc = None interface = None metadata = None opcodes = None src_map = None src_map_runtime = None user_doc = None def __init__(self, address=None): """Create a new smart contract proxy object. :param address: Contract address as 0x hex string """ if self.web3 is None: raise AttributeError( 'The `Contract` class has not been initialized. Please use the ' '`web3.contract` interface to create your contract class.' ) if address: self.address = normalize_address(self.web3.ens, address) if not self.address: raise TypeError("The address argument is required to instantiate a contract.") self.functions = ContractFunctions(self.abi, self.web3, self.address) self.caller = ContractCaller(self.abi, self.web3, self.address) self.events = ContractEvents(self.abi, self.web3, self.address) self.fallback = Contract.get_fallback_function(self.abi, self.web3, self.address) @classmethod def factory(cls, web3, class_name=None, **kwargs): kwargs['web3'] = web3 normalizers = { 'abi': normalize_abi, 'address': partial(normalize_address, kwargs['web3'].ens), 'bytecode': normalize_bytecode, 'bytecode_runtime': normalize_bytecode, } contract = PropertyCheckingFactory( class_name or cls.__name__, (cls,), kwargs, normalizers=normalizers, ) contract.functions = ContractFunctions(contract.abi, contract.web3) contract.caller = ContractCaller(contract.abi, contract.web3, contract.address) contract.events = ContractEvents(contract.abi, contract.web3) contract.fallback = Contract.get_fallback_function(contract.abi, contract.web3) return contract # # Contract Methods # @classmethod def constructor(cls, *args, **kwargs): """ :param args: The contract constructor arguments as positional arguments :param kwargs: The contract constructor arguments as keyword arguments :return: a contract constructor object """ if cls.bytecode is None: raise ValueError( "Cannot call constructor on a contract that does not have 'bytecode' associated " "with it" ) return ContractConstructor(cls.web3, cls.abi, cls.bytecode, *args, **kwargs) # Public API # @combomethod def encodeABI(cls, fn_name, args=None, kwargs=None, data=None): """ Encodes the arguments using the Ethereum ABI for the contract function that matches the given name and arguments.. :param data: defaults to function selector """ fn_abi, fn_selector, fn_arguments = get_function_info( fn_name, contract_abi=cls.abi, args=args, kwargs=kwargs, ) if data is None: data = fn_selector return encode_abi(cls.web3, fn_abi, fn_arguments, data) @combomethod def all_functions(self): return find_functions_by_identifier( self.abi, self.web3, self.address, lambda _: True ) @combomethod def get_function_by_signature(self, signature): if ' ' in signature: raise ValueError( 'Function signature should not contain any spaces. ' 'Found spaces in input: %s' % signature ) def callable_check(fn_abi): return abi_to_signature(fn_abi) == signature fns = find_functions_by_identifier(self.abi, self.web3, self.address, callable_check) return get_function_by_identifier(fns, 'signature') @combomethod def find_functions_by_name(self, fn_name): def callable_check(fn_abi): return fn_abi['name'] == fn_name return find_functions_by_identifier( self.abi, self.web3, self.address, callable_check ) @combomethod def get_function_by_name(self, fn_name): fns = self.find_functions_by_name(fn_name) return get_function_by_identifier(fns, 'name') @combomethod def get_function_by_selector(self, selector): def callable_check(fn_abi): return encode_hex(function_abi_to_4byte_selector(fn_abi)) == to_4byte_hex(selector) fns = find_functions_by_identifier(self.abi, self.web3, self.address, callable_check) return get_function_by_identifier(fns, 'selector') @combomethod def decode_function_input(self, data): data = HexBytes(data) selector, params = data[:4], data[4:] func = self.get_function_by_selector(selector) names = [x['name'] for x in func.abi['inputs']] types = [x['type'] for x in func.abi['inputs']] decoded = decode_abi(types, params) normalized = map_abi_data(BASE_RETURN_NORMALIZERS, types, decoded) return func, dict(zip(names, normalized)) @combomethod def find_functions_by_args(self, *args): def callable_check(fn_abi): return check_if_arguments_can_be_encoded(fn_abi, args=args, kwargs={}) return find_functions_by_identifier( self.abi, self.web3, self.address, callable_check ) @combomethod def get_function_by_args(self, *args): fns = self.find_functions_by_args(*args) return get_function_by_identifier(fns, 'args') # # Private Helpers # _return_data_normalizers = tuple() @classmethod def _prepare_transaction(cls, fn_name, fn_args=None, fn_kwargs=None, transaction=None): return prepare_transaction( cls.address, cls.web3, fn_identifier=fn_name, contract_abi=cls.abi, transaction=transaction, fn_args=fn_args, fn_kwargs=fn_kwargs, ) @classmethod def _find_matching_fn_abi(cls, fn_identifier=None, args=None, kwargs=None): return find_matching_fn_abi(cls.abi, fn_identifier=fn_identifier, args=args, kwargs=kwargs) @classmethod def _find_matching_event_abi(cls, event_name=None, argument_names=None): return find_matching_event_abi( abi=cls.abi, event_name=event_name, argument_names=argument_names) @staticmethod def get_fallback_function(abi, web3, address=None): if abi and fallback_func_abi_exists(abi): return ContractFunction.factory( 'fallback', web3=web3, contract_abi=abi, address=address, function_identifier=FallbackFn)() return NonExistentFallbackFunction() @combomethod def _encode_constructor_data(cls, args=None, kwargs=None): constructor_abi = get_constructor_abi(cls.abi) if constructor_abi: if args is None: args = tuple() if kwargs is None: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) deploy_data = add_0x_prefix( encode_abi(cls.web3, constructor_abi, arguments, data=cls.bytecode) ) else: deploy_data = to_hex(cls.bytecode) return deploy_data def mk_collision_prop(fn_name): def collision_fn(): msg = "Namespace collision for function name {0} with ConciseContract API.".format(fn_name) raise AttributeError(msg) collision_fn.__name__ = fn_name return collision_fn class ContractConstructor: """ Class for contract constructor API. """ def __init__(self, web3, abi, bytecode, *args, **kwargs): self.web3 = web3 self.abi = abi self.bytecode = bytecode self.data_in_transaction = self._encode_data_in_transaction(*args, **kwargs) @combomethod def _encode_data_in_transaction(self, *args, **kwargs): constructor_abi = get_constructor_abi(self.abi) if constructor_abi: if not args: args = tuple() if not kwargs: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) data = add_0x_prefix( encode_abi(self.web3, constructor_abi, arguments, data=self.bytecode) ) else: data = to_hex(self.bytecode) return data @combomethod def estimateGas(self, transaction=None): if transaction is None: estimate_gas_transaction = {} else: estimate_gas_transaction = dict(**transaction) self.check_forbidden_keys_in_transaction(estimate_gas_transaction, ["data", "to"]) if self.web3.eth.defaultAccount is not empty: estimate_gas_transaction.setdefault('from', self.web3.eth.defaultAccount) estimate_gas_transaction['data'] = self.data_in_transaction return self.web3.eth.estimateGas(estimate_gas_transaction) @combomethod def transact(self, transaction=None): if transaction is None: transact_transaction = {} else: transact_transaction = dict(**transaction) self.check_forbidden_keys_in_transaction(transact_transaction, ["data", "to"]) if self.web3.eth.defaultAccount is not empty: transact_transaction.setdefault('from', self.web3.eth.defaultAccount) transact_transaction['data'] = self.data_in_transaction # TODO: handle asynchronous contract creation return self.web3.eth.sendTransaction(transact_transaction) @combomethod def buildTransaction(self, transaction=None): """ Build the transaction dictionary without sending """ if transaction is None: built_transaction = {} else: built_transaction = dict(**transaction) self.check_forbidden_keys_in_transaction(built_transaction, ["data", "to"]) if self.web3.eth.defaultAccount is not empty: built_transaction.setdefault('from', self.web3.eth.defaultAccount) built_transaction['data'] = self.data_in_transaction built_transaction['to'] = b'' return fill_transaction_defaults(self.web3, built_transaction) @staticmethod def check_forbidden_keys_in_transaction(transaction, forbidden_keys=None): keys_found = set(transaction.keys()) & set(forbidden_keys) if keys_found: raise ValueError("Cannot set {} in transaction".format(', '.join(keys_found))) class ConciseMethod: ALLOWED_MODIFIERS = {'call', 'estimateGas', 'transact', 'buildTransaction'} def __init__(self, function, normalizers=None): self._function = function self._function._return_data_normalizers = normalizers def __call__(self, *args, **kwargs): return self.__prepared_function(*args, **kwargs) def __prepared_function(self, *args, **kwargs): if not kwargs: modifier, modifier_dict = 'call', {} elif len(kwargs) == 1: modifier, modifier_dict = kwargs.popitem() if modifier not in self.ALLOWED_MODIFIERS: raise TypeError( "The only allowed keyword arguments are: %s" % self.ALLOWED_MODIFIERS) else: raise TypeError("Use up to one keyword argument, one of: %s" % self.ALLOWED_MODIFIERS) return getattr(self._function(*args), modifier)(modifier_dict) class ConciseContract: """ An alternative Contract Factory which invokes all methods as `call()`, unless you add a keyword argument. The keyword argument assigns the prep method. This call > contract.withdraw(amount, transact={'from': eth.accounts[1], 'gas': 100000, ...}) is equivalent to this call in the classic contract: > contract.functions.withdraw(amount).transact({'from': eth.accounts[1], 'gas': 100000, ...}) """ @deprecated_for( "contract.caller.<method name> or contract.caller({transaction_dict}).<method name>" ) def __init__(self, classic_contract, method_class=ConciseMethod): classic_contract._return_data_normalizers += CONCISE_NORMALIZERS self._classic_contract = classic_contract self.address = self._classic_contract.address protected_fn_names = [fn for fn in dir(self) if not fn.endswith('__')] for fn_name in self._classic_contract.functions: # Override namespace collisions if fn_name in protected_fn_names: _concise_method = mk_collision_prop(fn_name) else: _classic_method = getattr( self._classic_contract.functions, fn_name) _concise_method = method_class( _classic_method, self._classic_contract._return_data_normalizers ) setattr(self, fn_name, _concise_method) @classmethod def factory(cls, *args, **kwargs): return compose(cls, Contract.factory(*args, **kwargs)) def _none_addr(datatype, data): if datatype == 'address' and int(data, base=16) == 0: return (datatype, None) else: return (datatype, data) CONCISE_NORMALIZERS = ( _none_addr, ) class ImplicitMethod(ConciseMethod): def __call_by_default(self, args): function_abi = find_matching_fn_abi(self._function.contract_abi, fn_identifier=self._function.function_identifier, args=args) return function_abi['constant'] if 'constant' in function_abi.keys() else False @deprecated_for("classic contract syntax. Ex: contract.functions.withdraw(amount).transact({})") def __call__(self, *args, **kwargs): # Modifier is not provided and method is not constant/pure do a transaction instead if not kwargs and not self.__call_by_default(args): return super().__call__(*args, transact={}) else: return super().__call__(*args, **kwargs) class ImplicitContract(ConciseContract): """ ImplicitContract class is similar to the ConciseContract class however it performs a transaction instead of a call if no modifier is given and the method is not marked 'constant' in the ABI. The transaction will use the default account to send the transaction. This call > contract.withdraw(amount) is equivalent to this call in the classic contract: > contract.functions.withdraw(amount).transact({}) """ def __init__(self, classic_contract, method_class=ImplicitMethod): super().__init__(classic_contract, method_class=method_class) class NonExistentFallbackFunction: @staticmethod def _raise_exception(): raise FallbackNotFound("No fallback function was found in the contract ABI.") def __getattr__(self, attr): return NonExistentFallbackFunction._raise_exception class ContractFunction: """Base class for contract functions A function accessed via the api contract.functions.myMethod(*args, **kwargs) is a subclass of this class. """ address = None function_identifier = None web3 = None contract_abi = None abi = None transaction = None arguments = None def __init__(self, abi=None): self.abi = abi self.fn_name = type(self).__name__ def __call__(self, *args, **kwargs): clone = copy.copy(self) if args is None: clone.args = tuple() else: clone.args = args if kwargs is None: clone.kwargs = {} else: clone.kwargs = kwargs clone._set_function_info() return clone def _set_function_info(self): if not self.abi: self.abi = find_matching_fn_abi( self.contract_abi, self.function_identifier, self.args, self.kwargs ) if self.function_identifier is FallbackFn: self.selector = encode_hex(b'') elif is_text(self.function_identifier): self.selector = encode_hex(function_abi_to_4byte_selector(self.abi)) else: raise TypeError("Unsupported function identifier") self.arguments = merge_args_and_kwargs(self.abi, self.args, self.kwargs) def call(self, transaction=None, block_identifier='latest'): """ Execute a contract function call using the `eth_call` interface. This method prepares a ``Caller`` object that exposes the contract functions and public variables as callable Python functions. Reading a public ``owner`` address variable example: .. code-block:: python ContractFactory = w3.eth.contract( abi=wallet_contract_definition["abi"] ) # Not a real contract address contract = ContractFactory("0x2f70d3d26829e412A602E83FE8EeBF80255AEeA5") # Read "owner" public variable addr = contract.functions.owner().call() :param transaction: Dictionary of transaction info for web3 interface :return: ``Caller`` object that has contract public functions and variables exposed as Python methods """ if transaction is None: call_transaction = {} else: call_transaction = dict(**transaction) if 'data' in call_transaction: raise ValueError("Cannot set data in call transaction") if self.address: call_transaction.setdefault('to', self.address) if self.web3.eth.defaultAccount is not empty: call_transaction.setdefault('from', self.web3.eth.defaultAccount) if 'to' not in call_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.[methodtype].[method].call()` from" " a contract factory you " "must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) block_id = parse_block_identifier(self.web3, block_identifier) return call_contract_function( self.web3, self.address, self._return_data_normalizers, self.function_identifier, call_transaction, block_id, self.contract_abi, self.abi, *self.args, **self.kwargs ) def transact(self, transaction=None): if transaction is None: transact_transaction = {} else: transact_transaction = dict(**transaction) if 'data' in transact_transaction: raise ValueError("Cannot set data in transact transaction") if self.address is not None: transact_transaction.setdefault('to', self.address) if self.web3.eth.defaultAccount is not empty: transact_transaction.setdefault('from', self.web3.eth.defaultAccount) if 'to' not in transact_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.transact` from a contract factory you " "must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) return transact_with_contract_function( self.address, self.web3, self.function_identifier, transact_transaction, self.contract_abi, self.abi, *self.args, **self.kwargs ) def estimateGas(self, transaction=None): if transaction is None: estimate_gas_transaction = {} else: estimate_gas_transaction = dict(**transaction) if 'data' in estimate_gas_transaction: raise ValueError("Cannot set data in estimateGas transaction") if 'to' in estimate_gas_transaction: raise ValueError("Cannot set to in estimateGas transaction") if self.address: estimate_gas_transaction.setdefault('to', self.address) if self.web3.eth.defaultAccount is not empty: estimate_gas_transaction.setdefault('from', self.web3.eth.defaultAccount) if 'to' not in estimate_gas_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.estimateGas` from a contract factory " "you must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) return estimate_gas_for_function( self.address, self.web3, self.function_identifier, estimate_gas_transaction, self.contract_abi, self.abi, *self.args, **self.kwargs ) def buildTransaction(self, transaction=None): """ Build the transaction dictionary without sending """ if transaction is None: built_transaction = {} else: built_transaction = dict(**transaction) if 'data' in built_transaction: raise ValueError("Cannot set data in build transaction") if not self.address and 'to' not in built_transaction: raise ValueError( "When using `ContractFunction.buildTransaction` from a contract factory " "you must provide a `to` address with the transaction" ) if self.address and 'to' in built_transaction: raise ValueError("Cannot set to in contract call build transaction") if self.address: built_transaction.setdefault('to', self.address) if 'to' not in built_transaction: raise ValueError( "Please ensure that this contract instance has an address." ) return build_transaction_for_function( self.address, self.web3, self.function_identifier, built_transaction, self.contract_abi, self.abi, *self.args, **self.kwargs ) @combomethod def _encode_transaction_data(cls): return add_0x_prefix(encode_abi(cls.web3, cls.abi, cls.arguments, cls.selector)) _return_data_normalizers = tuple() @classmethod def factory(cls, class_name, **kwargs): return PropertyCheckingFactory(class_name, (cls,), kwargs)(kwargs.get('abi')) def __repr__(self): if self.abi: _repr = '<Function %s' % abi_to_signature(self.abi) if self.arguments is not None: _repr += ' bound to %r' % (self.arguments,) return _repr + '>' return '<Function %s>' % self.fn_name class ContractEvent: """Base class for contract events An event accessed via the api contract.events.myEvents(*args, **kwargs) is a subclass of this class. """ address = None event_name = None web3 = None contract_abi = None abi = None def __init__(self, *argument_names): if argument_names is None: self.argument_names = tuple() else: self.argument_names = argument_names self.abi = self._get_event_abi() @classmethod def _get_event_abi(cls): return find_matching_event_abi( cls.contract_abi, event_name=cls.event_name) @combomethod def processReceipt(self, txn_receipt): return self._parse_logs(txn_receipt) @to_tuple def _parse_logs(self, txn_receipt): for log in txn_receipt['logs']: try: decoded_log = get_event_data(self.abi, log) except MismatchedABI: continue yield decoded_log @combomethod def createFilter( self, *, # PEP 3102 argument_filters=None, fromBlock=None, toBlock="latest", address=None, topics=None): """ Create filter object that tracks logs emitted by this contract event. :param filter_params: other parameters to limit the events """ if fromBlock is None: raise TypeError("Missing mandatory keyword argument to createFilter: fromBlock") if argument_filters is None: argument_filters = dict() _filters = dict(**argument_filters) event_abi = self._get_event_abi() check_for_forbidden_api_filter_arguments(event_abi, _filters) _, event_filter_params = construct_event_filter_params( self._get_event_abi(), contract_address=self.address, argument_filters=_filters, fromBlock=fromBlock, toBlock=toBlock, address=address, topics=topics, ) filter_builder = EventFilterBuilder(event_abi) filter_builder.address = event_filter_params.get('address') filter_builder.fromBlock = event_filter_params.get('fromBlock') filter_builder.toBlock = event_filter_params.get('toBlock') match_any_vals = { arg: value for arg, value in _filters.items() if not is_array_type(filter_builder.args[arg].arg_type) and is_list_like(value) } for arg, value in match_any_vals.items(): filter_builder.args[arg].match_any(*value) match_single_vals = { arg: value for arg, value in _filters.items() if not is_array_type(filter_builder.args[arg].arg_type) and not is_list_like(value) } for arg, value in match_single_vals.items(): filter_builder.args[arg].match_single(value) log_filter = filter_builder.deploy(self.web3) log_filter.log_entry_formatter = get_event_data(self._get_event_abi()) log_filter.builder = filter_builder return log_filter @combomethod def build_filter(self): builder = EventFilterBuilder( self._get_event_abi(), formatter=get_event_data(self._get_event_abi())) builder.address = self.address return builder @combomethod def getLogs(self, argument_filters=None, fromBlock=1, toBlock="latest"): """Get events for this contract instance using eth_getLogs API. This is a stateless method, as opposed to createFilter. It can be safely called against nodes which do not provide eth_newFilter API, like Infura nodes. If no block range is provided and there are many events, like ``Transfer`` events for a popular token, the Ethereum node might be overloaded and timeout on the underlying JSON-RPC call. Example - how to get all ERC-20 token transactions for the latest 10 blocks: .. code-block:: python from = max(mycontract.web3.eth.blockNumber - 10, 1) to = mycontract.web3.eth.blockNumber events = mycontract.events.Transfer.getLogs(fromBlock=from, toBlock=to) for e in events: print(e["args"]["from"], e["args"]["to"], e["args"]["value"]) The returned processed log values will look like: .. code-block:: python ( AttributeDict({ 'args': AttributeDict({}), 'event': 'LogNoArguments', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('...'), 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'blockHash': HexBytes('...'), 'blockNumber': 3 }), AttributeDict(...), ... ) See also: :func:`web3.middleware.filter.local_filter_middleware`. :param argument_filters: :param fromBlock: block number, defaults to 1 :param toBlock: block number or "latest". Defaults to "latest" :yield: Tuple of :class:`AttributeDict` instances """ if not self.address: raise TypeError("This method can be only called on " "an instated contract with an address") abi = self._get_event_abi() if argument_filters is None: argument_filters = dict() _filters = dict(**argument_filters) # Construct JSON-RPC raw filter presentation based on human readable Python descriptions # Namely, convert event names to their keccak signatures data_filter_set, event_filter_params = construct_event_filter_params( abi, contract_address=self.address, argument_filters=_filters, fromBlock=fromBlock, toBlock=toBlock, address=self.address, ) # Call JSON-RPC API logs = self.web3.eth.getLogs(event_filter_params) # Convert raw binary data to Python proxy objects as described by ABI return tuple(get_event_data(abi, entry) for entry in logs) @classmethod def factory(cls, class_name, **kwargs): return PropertyCheckingFactory(class_name, (cls,), kwargs) class ContractCaller: """ An alternative Contract API. This call: > contract.caller({'from': eth.accounts[1], 'gas': 100000, ...}).add(2, 3) is equivalent to this call in the classic contract: > contract.functions.add(2, 3).call({'from': eth.accounts[1], 'gas': 100000, ...}) Other options for invoking this class include: > contract.caller.add(2, 3) or > contract.caller().add(2, 3) or > contract.caller(transaction={'from': eth.accounts[1], 'gas': 100000, ...}).add(2, 3) """ def __init__(self, abi, web3, address, transaction=None, block_identifier='latest'): self.web3 = web3 self.address = address self.abi = abi self._functions = None if abi: if transaction is None: transaction = {} self._functions = filter_by_type('function', self.abi) for func in self._functions: fn = ContractFunction.factory( func['name'], web3=self.web3, contract_abi=self.abi, address=self.address, function_identifier=func['name']) block_id = parse_block_identifier(self.web3, block_identifier) caller_method = partial(self.call_function, fn, transaction=transaction, block_identifier=block_id) setattr(self, func['name'], caller_method) def __getattr__(self, function_name): if self.abi is None: raise NoABIFound( "There is no ABI found for this contract.", ) elif not self._functions or len(self._functions) == 0: raise NoABIFunctionsFound( "The ABI for this contract contains no function definitions. ", "Are you sure you provided the correct contract ABI?" ) elif function_name not in self._functions: functions_available = ', '.join([fn['name'] for fn in self._functions]) raise MismatchedABI( "The function '{}' was not found in this contract's ABI. ".format(function_name), "Here is a list of all of the function names found: ", "{}. ".format(functions_available), "Did you mean to call one of those functions?" ) else: return super().__getattribute__(function_name) def __call__(self, transaction=None, block_identifier='latest'): if transaction is None: transaction = {} return type(self)(self.abi, self.web3, self.address, transaction=transaction, block_identifier=block_identifier) @staticmethod def call_function(fn, *args, transaction=None, block_identifier='latest', **kwargs): if transaction is None: transaction = {} return fn(*args, **kwargs).call(transaction, block_identifier) def check_for_forbidden_api_filter_arguments(event_abi, _filters): name_indexed_inputs = {_input['name']: _input for _input in event_abi['inputs']} for filter_name, filter_value in _filters.items(): _input = name_indexed_inputs[filter_name] if is_array_type(_input['type']): raise TypeError( "createFilter no longer supports array type filter arguments. " "see the build_filter method for filtering array type filters.") if is_list_like(filter_value) and is_dynamic_sized_type(_input['type']): raise TypeError( "createFilter no longer supports setting filter argument options for dynamic sized " "types. See the build_filter method for setting filters with the match_any " "method.") def call_contract_function( web3, address, normalizers, function_identifier, transaction, block_id=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ Helper function for interacting with a contract function using the `eth_call` API. """ call_transaction = prepare_transaction( address, web3, fn_identifier=function_identifier, contract_abi=contract_abi, fn_abi=fn_abi, transaction=transaction, fn_args=args, fn_kwargs=kwargs, ) if block_id is None: return_data = web3.eth.call(call_transaction) else: return_data = web3.eth.call(call_transaction, block_identifier=block_id) if fn_abi is None: fn_abi = find_matching_fn_abi(contract_abi, function_identifier, args, kwargs) output_types = get_abi_output_types(fn_abi) try: output_data = decode_abi(output_types, return_data) except DecodingError as e: # Provide a more helpful error message than the one provided by # eth-abi-utils is_missing_code_error = ( return_data in ACCEPTABLE_EMPTY_STRINGS and web3.eth.getCode(address) in ACCEPTABLE_EMPTY_STRINGS ) if is_missing_code_error: msg = ( "Could not transact with/call contract function, is contract " "deployed correctly and chain synced?" ) else: msg = ( "Could not decode contract function call {} return data {} for " "output_types {}".format( function_identifier, return_data, output_types ) ) raise BadFunctionCallOutput(msg) from e _normalizers = itertools.chain( BASE_RETURN_NORMALIZERS, normalizers, ) normalized_data = map_abi_data(_normalizers, output_types, output_data) if len(normalized_data) == 1: return normalized_data[0] else: return normalized_data def parse_block_identifier(web3, block_identifier): if isinstance(block_identifier, int): return parse_block_identifier_int(web3, block_identifier) elif block_identifier in ['latest', 'earliest', 'pending']: return block_identifier elif isinstance(block_identifier, bytes) or is_hex_encoded_block_hash(block_identifier): return web3.eth.getBlock(block_identifier)['number'] else: raise BlockNumberOutofRange def parse_block_identifier_int(web3, block_identifier_int): if block_identifier_int >= 0: block_num = block_identifier_int else: last_block = web3.eth.getBlock('latest')['number'] block_num = last_block + block_identifier_int + 1 if block_num < 0: raise BlockNumberOutofRange return block_num def transact_with_contract_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ Helper function for interacting with a contract function by sending a transaction. """ transact_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, transaction=transaction, fn_abi=fn_abi, fn_args=args, fn_kwargs=kwargs, ) txn_hash = web3.eth.sendTransaction(transact_transaction) return txn_hash def estimate_gas_for_function( address, web3, fn_identifier=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """Estimates gas cost a function call would take. Don't call this directly, instead use :meth:`Contract.estimateGas` on your contract instance. """ estimate_transaction = prepare_transaction( address, web3, fn_identifier=fn_identifier, contract_abi=contract_abi, fn_abi=fn_abi, transaction=transaction, fn_args=args, fn_kwargs=kwargs, ) gas_estimate = web3.eth.estimateGas(estimate_transaction) return gas_estimate def build_transaction_for_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """Builds a dictionary with the fields required to make the given transaction Don't call this directly, instead use :meth:`Contract.buildTransaction` on your contract instance. """ prepared_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, fn_abi=fn_abi, transaction=transaction, fn_args=args, fn_kwargs=kwargs, ) prepared_transaction = fill_transaction_defaults(web3, prepared_transaction) return prepared_transaction def find_functions_by_identifier(contract_abi, web3, address, callable_check): fns_abi = filter_by_type('function', contract_abi) return [ ContractFunction.factory( fn_abi['name'], web3=web3, contract_abi=contract_abi, address=address, function_identifier=fn_abi['name'], abi=fn_abi ) for fn_abi in fns_abi if callable_check(fn_abi) ] def get_function_by_identifier(fns, identifier): if len(fns) > 1: raise ValueError( 'Found multiple functions with matching {0}. ' 'Found: {1!r}'.format(identifier, fns) ) elif len(fns) == 0: raise ValueError( 'Could not find any function with matching {0}'.format(identifier) ) return fns[0]
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/contract.py
contract.py