from iconsdk.signed_transaction import SignedTransaction
from iconsdk.utils.convert_type import convert_hex_str_to_int
from iconsdk.wallet.wallet import KeyWallet
from quickstart.examples.test.constant import (TEST_HTTP_ENDPOINT_URI_V3,
                                               TEST_PRIVATE_KEY,
                                               SCORE_INSTALL_ADDRESS,
                                               GOVERNANCE_ADDRESS)
from quickstart.examples.util.repeater import retry

current_dir_path = path.abspath(path.dirname(__file__))
score_path_standard_token = path.join(current_dir_path,
                                      'sample_data/standard_token.zip')
score_path_sample_token = path.join(current_dir_path,
                                    'sample_data/sample_token.zip')
score_paths = [score_path_sample_token, score_path_standard_token]
icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))


# Returns the max step limit
def get_max_step_limit():
    _param = {"contextType": "invoke"}
    _call = CallBuilder()\
        .from_(wallet1.get_address())\
        .to(GOVERNANCE_ADDRESS)\
        .method("getMaxStepLimit")\
        .params(_param)\
        .build()
    _result = icon_service.call(_call)
    return convert_hex_str_to_int(_result)

示例#2
0
def create_icon_service(url: str) -> IconService:
    url: str = get_url(url)
    return IconService(HTTPProvider(url))
示例#3
0
 def test_set_http_provider_with_param(self):
     icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))
     self.assertEqual(type(icon_service.get_block("latest")), dict)
示例#4
0
pd.set_option('display.width', desired_width)
pd.set_option('display.max_columns', 10)

currPath = os.getcwd()
projectPath = os.path.join(currPath, "06_wallet_ranking")
if not os.path.exists(projectPath):
    os.mkdir(projectPath)

walletPath = os.path.join(currPath, "wallet")
if not os.path.exists(walletPath):
    os.mkdir(walletPath)

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# using solidwallet
default_ctz_api = "https://ctz.solidwallet.io/api/v3"
icon_service = IconService(HTTPProvider(default_ctz_api))

## Creating Wallet if does not exist (only done for the first time)
tester_wallet = os.path.join(walletPath, "test_keystore_1")

if os.path.exists(tester_wallet):
    wallet = KeyWallet.load(tester_wallet, "abcd1234*")
else:
    wallet = KeyWallet.create()
    wallet.get_address()
    wallet.get_private_key()
    wallet.store(tester_wallet, "abcd1234*")

tester_address = wallet.get_address()

示例#5
0
from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider
from iconsdk.exception import JSONRPCException
from iconsdk.builder.transaction_builder import CallTransactionBuilder, TransactionBuilder, DeployTransactionBuilder
from iconsdk.builder.call_builder import CallBuilder
from iconsdk.signed_transaction import SignedTransaction
from .repeater import retry

SCORE_ADDRESS = ''
icon_service = IconService(HTTPProvider("https://bicon.net.solidwallet.io", 3))
RANDOM_ADDRESS = 'hx8b94a3792f336b71937709dae5487166c180c87a'


def get_score_addr(score_address):
    global SCORE_ADDRESS
    SCORE_ADDRESS = score_address


def external(fn_name: str, wallet, params=None):
    call_transaction = CallTransactionBuilder()\
          .from_(wallet.get_address())\
          .to(SCORE_ADDRESS)\
          .nid(3)\
          .nonce(100)\
          .method(fn_name)\
          .params(params)\
          .build()
    transaction(call_transaction, wallet)


def payable(fn_name: str, wallet, value, params=None):
示例#6
0
 def setUpClass(cls):
     cls.icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))
     # Because governance always has score apis, it is proper for the test.
     cls.governance_address = "cx0000000000000000000000000000000000000001"
示例#7
0
import ast

from iconsdk.builder.call_builder import CallBuilder
from iconsdk.builder.transaction_builder import CallTransactionBuilder
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider
from iconsdk.wallet.wallet import KeyWallet

import config

CASINO_SCORE_ADDRESS = config.CASINO_SCORE_ADDRESS
BET_AMOUNT = config.BET_AMOUNT

icon_service = IconService(HTTPProvider(config.ICON_SERVICE_PROVIDER_URL))

player_wallet = KeyWallet.load(
    config.PLAYER_WALLET_PRIVATE_KEY_FILE_PATH, config.PLAYER_WALLET_PASSWORD
)

def get_wallet_balance(wallet_address):
    return icon_service.get_balance(wallet_address)


def get_casino_balance():
    return get_wallet_balance(CASINO_SCORE_ADDRESS)


def get_player_balance():
    return get_wallet_balance(player_wallet.get_address())
示例#8
0
    def deploy(self, conf: dict) -> dict:
        """Deploy SCORE on the server.
        :param conf: deploy command configuration
        """
        # check keystore, and get password from user's terminal input
        password = conf.get('password', None)
        password = self._check_deploy(conf, password)

        if conf['mode'] == 'install':
            score_address = f'cx{"0"*40}'
        else:
            score_address = conf['to']

        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        if password:
            try:
                wallet = KeyWallet.load(conf['keyStore'], password)
                from_ = wallet.get_address()

            except KeyStoreException as e:
                print(e.args[0])
                return None
        else:
            # make dummy wallet
            wallet = KeyWallet.create()
            from_ = conf['from']

        # make zip and convert to hexadecimal string data (start with 0x) and return
        content = gen_deploy_data_content(conf['project'])

        deploy_transaction = DeployTransactionBuilder() \
            .from_(from_) \
            .to(score_address) \
            .nid(convert_hex_str_to_int(conf['nid'])) \
            .content_type("application/zip") \
            .content(content) \
            .params(conf.get('scoreParams', {})) \
            .build()

        if 'stepLimit' not in conf:
            step_limit = icon_service.estimate_step(deploy_transaction) + 10000
        else:
            step_limit = convert_hex_str_to_int(conf['stepLimit'])

        deploy_transaction.step_limit = step_limit

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(deploy_transaction, wallet)

        if not password:
            signed_transaction.signed_transaction_dict['signature'] = 'sig'

        # Sends transaction and return response
        response = send_transaction_with_logger(icon_service,
                                                signed_transaction, uri)

        if 'error' in response:
            print('Got an error response')
            print(json.dumps(response, indent=4))
        else:
            print('Send deploy request successfully.')
            tx_hash = response['result']
            print(
                f'If you want to check SCORE deployed successfully, execute txresult command'
            )
            print(f"transaction hash: {tx_hash}")

        return response
def get_new_icx_service():
    svc = IconService(HTTPProvider("https://ctz.solidwallet.io/api/v3"))
    return IcxService(svc)
import json
from pprint import pprint

from iconsdk.builder.call_builder import CallBuilder
from iconsdk.builder.transaction_builder import CallTransactionBuilder
from iconsdk.exception import JSONRPCException
from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.utils.convert_type import convert_hex_str_to_int
from iconsdk.wallet.wallet import KeyWallet

from repeater import retry

icon_service = IconService(
    HTTPProvider("https://icon-27107-test.morpheuslabs.io"))

wallet = KeyWallet.create()
print("address: ", wallet.get_address())  # Returns an address
print("private key: ", wallet.get_private_key())  # Returns a private key

# file_path = "./test_keystore.json"
# wallet.store(file_path, "a12345678");
    :param to: from account id or wallet address
    :param amount: amount to transfer
    :return:
    """

    params = {"account_id": convert_int_to_hex_str(account_id), "token_type": token_type,
              "contract_addr": contract_addr,
              "to": to,
              "amount": convert_int_to_hex_str(amount)}

    transaction = CallTransactionBuilder()\
        .from_(wallet.get_address())\
        .to(IconServiceContainer.contract_addr)\
        .step_limit(100000000000000)\
        .nid(3)\
        .nonce(2) \
        .method("transfer") \
        .params(params) \
        .build()

    result = _send_transaction(transaction, wallet, 9)
    for log in result['eventLogs']:
        if log['indexed'] == ['Pending(str)']:
            return json.loads(log['data'][0])


if __name__ == '__main__':
    wallet = KeyWallet.create()
    IconServiceContainer.icon_service = IconService(HTTPProvider("http://localhost:9000/api/v3"))
    app.run(port=3004)
示例#12
0
import json
import datetime
from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider

icon_service = IconService(HTTPProvider("http://104.196.209.29:9000/api/v3"))

#Define latest block, latest block height, and latest block timestamp.
latest_block = json.loads(json.dumps(icon_service.get_block("latest")))
latest_block_height = latest_block['height']
latest_block_timestamp_epoch = latest_block['time_stamp']
latest_block_timestamp_utc = datetime.datetime.utcfromtimestamp(
    latest_block_timestamp_epoch / 1000000.0).strftime('%Y-%m-%d %H:%M:%S.%f')

#Print latest block heigh and latest block timestamp.
print("Latest Block Height: " + str(latest_block_height))
print("Latest Block Timestamp: " + str(latest_block_timestamp_utc) + " UTC")

#Calculate block time of most recent block.
#block_time = (latest_block_timestamp - prev_block_timestamp)/1000000
#print("Block Time:",block_time,"seconds")

#Calculate average block time from last 10 blocks.
icx_block_time_list = []
for x in range(10):
    icx_block = json.loads(
        json.dumps(icon_service.get_block(latest_block_height - x)))
    icx_block_prev = json.loads(
        json.dumps(icon_service.get_block(latest_block_height - x - 1)))
    icx_block_timestamp = icx_block['time_stamp']
    icx_block_prev_timestamp = icx_block_prev['time_stamp']
示例#13
0
 def setUpClass(cls):
     cls.icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))
示例#14
0
 def setUpClass(cls):
     cls.icon_service = IconService(HTTPProvider(BASE_DOMAIN_URL_V3_FOR_TEST, VERSION_FOR_TEST))
示例#15
0
 def setUpClass(cls):
     cls.wallet = KeyWallet.create()
     cls.address = cls.wallet.get_address()
     cls.to = "cx0000000000000000000000000000000000000001"
     cls.icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))
示例#16
0
    def setUp(self):
        super().setUp(block_confirm_interval=1, network_only=True)

        # if you want to send request to network, uncomment next line and set self.TEST_HTTP_ENDPOINT_URI_V3
        self.icon_service = IconService(
            HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))
示例#17
0
    def transfer(self, conf: dict) -> dict:
        """Transfer ICX Coin.

        :param conf: transfer command configuration.
        :return: response of transfer.
        """
        # check value type (must be int), address and keystore file
        # if valid, return user input password
        password = conf.get('password', None)
        password = self._check_transfer(conf, password)

        if password:
            try:
                wallet = KeyWallet.load(conf['keyStore'], password)
                from_ = wallet.get_address()

            except KeyStoreException as e:
                print(e.args[0])
                return None
        else:
            # make dummy wallet
            wallet = KeyWallet.create()
            from_ = conf['from']

        uri, version = uri_parser(conf['uri'])
        icon_service = IconService(HTTPProvider(uri, version))

        transaction = TransactionBuilder() \
            .from_(from_) \
            .to(conf['to']) \
            .value(int(conf['value'])) \
            .nid(convert_hex_str_to_int(conf['nid'])) \
            .timestamp(int(time() * 10 ** 6)) \
            .build()

        if 'stepLimit' not in conf:
            step_limit = icon_service.estimate_step(transaction)
        else:
            step_limit = convert_hex_str_to_int(conf['stepLimit'])

        transaction.step_limit = step_limit

        # Returns the signed transaction object having a signature
        signed_transaction = SignedTransaction(transaction, wallet)

        if not password:
            signed_transaction.signed_transaction_dict['signature'] = 'sig'

        # Sends transaction and return response
        response = send_transaction_with_logger(icon_service,
                                                signed_transaction, uri)

        if 'result' in response:
            print('Send transfer request successfully.')
            tx_hash = response['result']
            print(f"transaction hash: {tx_hash}")
        else:
            print('Got an error response')
            print(json.dumps(response, indent=4))

        return response
from iconsdk.builder.transaction_builder import CallTransactionBuilder
from iconsdk.exception import JSONRPCException
from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.utils.convert_type import convert_hex_str_to_int
from iconsdk.wallet.wallet import KeyWallet

from repeater import retry

app = Flask(__name__)
default_account = 'hx86f8117539f039f7c6b5a8ca8d233e2e752bd8fa'
default_score = "cx26da99fcddd7f06a0e565e0e3edde3d1218ff5da"  # voting smart contract address
icon_node_rpc = "http://bops-t.morpheuslabs.io:27107/api/v3"
# internal RPC node URL
icon_service = IconService(HTTPProvider(icon_node_rpc))

wallets = {
    'wallet1':
    KeyWallet.load(
        bytes.fromhex(
            "fb9164edaf46e254917694e3ea7daa65796c6899d2382c977fd9e8ffd995f348")
    ),
    'wallet2':
    KeyWallet.load(
        bytes.fromhex(
            "19d8fa5a7dcb3ab6aa1a6348a88007bf100827f43c26457d01ca0260711ac2df")
    ),
    'wallet3':
    KeyWallet.load(
        bytes.fromhex(
示例#19
0
 def setUpClass(cls):
     cls.icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))
     result = cls.icon_service.get_block(1)
     cls.tx_hash = result["confirmed_transaction_list"][0]["txHash"]
     cls.tx_hash_invalid = "0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
示例#20
0
    def test_integrate_converter(self):
        """
        Test integrating for the converter which checks that all of the data
        about the block, transaction, and transaction result have the right format.

        [Purpose]
        Check all of the data about the block, transaction, and transaction result.

        [Scenario]
        1. Get the last block data and validate the block data.
        2. Get all of the transaction data on that block and validate the transaction data.
        3. Get all of the transaction result data on that transaction and validate the transaction result data.
        4. Repeatedly, get the other blocks from the last to the first and validate all of three kinds of the data.
        """
        test_domains = self.domains + [BASE_DOMAIN_URL_V3_FOR_TEST]
        max_block_height = 100
        for domain in test_domains:
            icon_service = IconService(HTTPProvider(domain, VERSION_FOR_TEST))
            last_block_height = icon_service.get_block("latest")["height"]
            block_versions = [BLOCK_0_1A_VERSION, BLOCK_0_3_VERSION]
            for block_version in block_versions:
                if block_version == BLOCK_0_1A_VERSION:
                    block_template = BLOCK_0_1a
                    key_name_of_transactions = 'confirmed_transaction_list'
                else:
                    # After Mainnet apply for block 0.3, remove this remark right away.
                    continue

                    block_template = BLOCK_0_3
                    key_name_of_transactions = 'transactions'

                for height in range(last_block_height if last_block_height <
                                    max_block_height else max_block_height):
                    # Check block
                    block = icon_service.get_block(height,
                                                   full_response=True,
                                                   block_version=block_version)
                    block = block['result']
                    converted_block = icon_service.get_block(
                        height, block_version=block_version)
                    block_template = get_block_template_to_convert_transactions_for_genesis(
                        block, block_template)
                    self.assertTrue(
                        validate_block(block_template, block, converted_block))

                    if block["height"] == 0:
                        continue

                    for transaction_in_block in converted_block[
                            key_name_of_transactions]:
                        # Check transaction result
                        tx_result = icon_service.get_transaction_result(
                            transaction_in_block["txHash"], True)
                        tx_result = tx_result['result']
                        converted_transaction_result = icon_service.get_transaction_result(
                            transaction_in_block["txHash"])
                        self.assertTrue(
                            validate_transaction_result(
                                TRANSACTION_RESULT, tx_result,
                                converted_transaction_result))

                        # Check transaction
                        transaction = icon_service.get_transaction(
                            transaction_in_block["txHash"], True)
                        transaction = transaction['result']
                        converted_transaction = icon_service.get_transaction(
                            transaction_in_block["txHash"])
                        self.assertTrue(
                            validate_transaction(TRANSACTION, transaction,
                                                 converted_transaction))
示例#21
0
    CallTransactionBuilder,
    MessageTransactionBuilder
)
from iconsdk.signed_transaction import SignedTransaction

localnet = "http://127.0.0.1:9000/api/v3"
network_id = 3
contract_address = "cx29b3171be7a6828ed7c1331f3adda1240782fdf2"
keystore_path = "./bongki"
keystore_pw = "bongki@3"

wallet = KeyWallet.load(keystore_path, keystore_pw)
tester_addr = wallet.get_address()
#tester_addr = "hxe7af5fcfd8dfc67530a01a0e403882687528dfcc"

icon_service = IconService(HTTPProvider(localnet))

#call = CallBuilder().from_(tester_addr)\
#                    .to(contract_address)\
#                    .method("hello")\
#                    .build()
#                    
#result = icon_service.call(call)
#print(result)

call = CallBuilder().from_(tester_addr)\
                    .to(contract_address)\
                    .method("balanceOf")\
                    .params({"_to":tester_addr})\
                    .build()
示例#22
0
from icon_transaction import call_transfer
from iconsdk.wallet.wallet import KeyWallet
from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider
from flask import Flask,request


icon_service = IconService(HTTPProvider('http://*****:*****@app.route('/transfer', methods=['POST'])
def home():
    req_json = request.get_json()

    from_key = req_json['from']
    to_key = req_json['to']
    value = req_json['value']

    call_transfer(from_key, to_key, value)
    print(from_key + ' -->' + to_key + ' :: ' + str(value) + '\n')
示例#23
0
import base64
import json
import requests
from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider
from iconsdk.builder.call_builder import CallBuilder
from iconsdk.builder.transaction_builder import (
    CallTransactionBuilder,
    MessageTransactionBuilder
)
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.wallet.wallet import KeyWallet

wallet = KeyWallet.load("keystore", "password123~~")
icx_api_endpoint = "http://localhost:9000/api/v3"
icon_service = IconService(HTTPProvider("http://localhost:9000", 3))
irc31_contract_address = "cx7bf6fc3501bc9478b822d197249fb03f1bf32c2f"

class MintToken:

	def __init__(self, tweet_id, tweet_user, tweet_body, tweet_image):
		self.tweet_id = tweet_id
		self.tweet_user = tweet_user
		self.tweet_body = tweet_body
		self.tweet_image = tweet_image

	def get_tweet_uri(self):
		params = {
			"_id": self.tweet_id
		}
		call = CallBuilder()\
 def setUp(self):
     self.wallet = KeyWallet.load(keystore_path, keystore_pw)
     self.tester_addr = self.wallet.get_address()
     self.icon_service = IconService(HTTPProvider(node_uri))
示例#25
0
def create_reader(url: str, nid: int) -> PRepToolsReader:
    url: str = get_url(url)
    icon_service = IconService(HTTPProvider(url))
    return PRepToolsReader(icon_service, nid)
import pymysql

from pytz import timezone

#---------------------------------------Icon SCORE Service--------------------------------------
import json
# SCORE's Dictionaty DB does not support List format, so we change the List format to JSON format

from iconsdk.icon_service import IconService
from iconsdk.providers.http_provider import HTTPProvider
from iconsdk.builder.transaction_builder import CallTransactionBuilder
from iconsdk.signed_transaction import SignedTransaction
from iconsdk.wallet.wallet import KeyWallet

#---------------------------------------Icon SerFvice rink---------------------------------------
icon_service = IconService(HTTPProvider("https://ctz.solidwallet.io/api/v3"))
# 아이콘 서비스 어느 주소단이랑 연동할 것인가
_score_address = "cx~~~~~~~"
# Deployed SCORE Address
_keystore_address = "hx~~~~~~~"
# The address of the wallet that will trigger the transaction
wallet = KeyWallet.load("key's full path", "key's password")
#
'''
#time check
t = time.time()
now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(t))
with open('/home/lyu/PycharmProjects/Without_Doubt_Project/Total_Crawler/log.txt', 'a+') as f:
    f.write(now+"\n")
'''
from iconsdk.utils.convert_type import convert_hex_str_to_int
from iconsdk.wallet.wallet import KeyWallet
from quickstart.examples.test.constant import (BASE_DOMAIN_URL_V3_FOR_TEST,
                                               PRIVATE_KEY_FOR_TEST,
                                               SCORE_INSTALL_ADDRESS,
                                               GOVERNANCE_ADDRESS,
                                               VERSION_FOR_TEST)
from quickstart.examples.util.repeater import retry

current_dir_path = path.abspath(path.dirname(__file__))
score_path_standard_token = path.join(current_dir_path,
                                      'sample_data/standard_token.zip')
score_path_sample_token = path.join(current_dir_path,
                                    'sample_data/sample_token.zip')
score_paths = [score_path_sample_token, score_path_standard_token]
icon_service = IconService(
    HTTPProvider(BASE_DOMAIN_URL_V3_FOR_TEST, VERSION_FOR_TEST))


# Returns the max step limit
def get_max_step_limit():
    _param = {"contextType": "invoke"}
    _call = CallBuilder()\
        .from_(wallet1.get_address())\
        .to(GOVERNANCE_ADDRESS)\
        .method("getMaxStepLimit")\
        .params(_param)\
        .build()
    _result = icon_service.call(_call)
    return convert_hex_str_to_int(_result)

 def setUpClass(cls):
     cls.icon_service = IconService(HTTPProvider(TEST_HTTP_ENDPOINT_URI_V3))
     result = cls.icon_service.get_block("latest")
     cls.valid_hash = add_0x_prefix(result["block_hash"])