diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 6aa4635..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index dfe0770..0000000 --- a/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Auto detect text files and perform LF normalization -* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b24d71e --- /dev/null +++ b/.gitignore @@ -0,0 +1,50 @@ +# These are some examples of commonly ignored file patterns. +# You should customize this list as applicable to your project. +# Learn more about .gitignore: +# https://www.atlassian.com/git/tutorials/saving-changes/gitignore + +# Node artifact files +node_modules/ +dist/ + +# Compiled Java class files +*.class + +# Compiled Python bytecode +*.py[cod] + +# Log files +*.log + +# Package files +*.jar + +# Maven +target/ +dist/ + +# JetBrains IDE +.idea/ + +# Unit test reports +TEST*.xml + +# Generated by MacOS +.DS_Store + +# Generated by Windows +Thumbs.db + +# Applications +*.app +*.exe +*.war + +# Large media files +*.mp4 +*.tiff +*.avi +*.flv +*.mov +*.wmv + diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..8974519 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "python.analysis.extraPaths": [ + "./modules" + ] +} \ No newline at end of file diff --git a/Base_API_Call.py b/Base_API_Call.py deleted file mode 100644 index 16f8d91..0000000 --- a/Base_API_Call.py +++ /dev/null @@ -1,47 +0,0 @@ -import json -import http.client - -class API: - def Call(call,payload,content,conn): - headers = { 'content-type': "application/json" } - - conn.request(call, content, payload, headers) - res = conn.getresponse() - data = res.read() - - return data.decode("utf-8") - - def Request_formatter(JSON): - Item = json.loads(JSON) - jsonrpc = Item["jsonrpc"] - id = Item["id"] - result = Item["result"] - - return result - - def Format(Call,Payload,Content,conn,form): - #Try - if conn == "test": - conn = "test" - if form == "JSON": - return API.Call(Call,Payload,Content,conn) - else: - JSON = API.Call(Call,Payload,Content,conn) - return API.clientVersion_formatter(JSON) - - else: - if form == "JSON": - return API.Call(Call,Payload,Content,conn) - else: - JSON = API.Call(Call,Payload,Content,conn) - return API.Request_formatter(JSON) - #Except - ##ERROR Handling - - def Tatum_Format(): - print("Base API") - - def Tatum_Request_Formater(): - print("Base API") - - diff --git a/EXECUTE_Test.py b/EXECUTE_Test.py deleted file mode 100644 index e8812d9..0000000 --- a/EXECUTE_Test.py +++ /dev/null @@ -1,97 +0,0 @@ -from web3 import web3_Request -from net import net_Request -from eth import eth_Request -from tatum import tatum_Request - -import hashlib - -class Test: - def __init__(self): - print("---------------- Starting Web3 Test ----------------") - #self.web3_test() - - print("---------------- Starting net Test ----------------") - #self.net_test() - - print("---------------- Starting eth Test ----------------") - #self.eth_test() - - print("---------------- Starting tatum Test ----------------") - self.tatum_test() - - - def web3_test(self): - String= "Q" - Hash = hashlib.sha256(String.encode('utf-8')).hexdigest() - #print(Hash) - - #print(web3_Request.clientVersion()) - #print(web3_Request.sha3(Hash=Hash)) - - def net_test(self): - print("none") - #print(net_Request.version()) - #print(net_Request.listening()) - #print(net_Request.peerCount()) - - def eth_test(self): - #print(int(eth_Request.protocolVersion(form="Text"),16)) - #print(eth_Request.syncing(form="Text")) - #print(eth_Request.coinbase(form="Text")) - print(eth_Request.gasPrice(form="Text")) - print(eth_Request.accounts(form="Text")) - print(eth_Request.blockNumber(form="Text")) - - - Addy = "0x438e0b511981FE8CF7283e981ca8c3394bB3646E" - #print(eth_Request.getBalance(Address=Addy,form="Text")) - - #print(eth_Request.getTransactionCount(form="Text")) - #print(eth_Request.getBlockTransactionCountByHash(form="Text")) - #print(eth_Request.getBlockTransactionCountByNumber(form="Text")) - #print(eth_Request.getCode(form="Text")) - #print(eth_Request.call(form="Text")) - #print(eth_Request.estimateGas(form="Text")) - #print(eth_Request.getBlockByHash(form="Text")) - #print(eth_Request.getBlockByNumber(form="Text")) - #print(eth_Request.getBlockSignersByNumber(form="Text")) - #print(eth_Request.getBlockSignersByHash(form="Text")) - #print(eth_Request.getBlockFinalityByNumber(form="Text")) - #print(eth_Request.getBlockFinalityByHash(form="Text")) - #print(eth_Request.getCandidateStatus(form="Text")) - #print(eth_Request.getTransactionByHash(form="Text")) - #print(eth_Request.getTransactionByBlockHashAndIndex(form="Text")) - #print(eth_Request.getTransactionByBlockNumberAndIndex(form="Text")) - #print(eth_Request.getTransactionReceipt(form="Text")) - - #ERRORS - #print(eth_Request.getCandidates()) - #print(eth_Request.sendRawTransaction()) - #print(eth_Request.getStorageAt()) - #print(eth_Request.sign()) - #print(eth_Request.sendTransaction()) - - def tatum_test(self): - API_KEY = "b56527b4-1db2-4842-b388-357a7ad44d2a" - Seed = "Quincy_JOJONONONO" - Hash = "0xead075790098c7261e9fad995183fcc6eb4c3102f22c2507fc0fc25bd2cd0aa9" - Address = "xdce4c4febe1cb34c3490167c163c9ed92049b32b5c" - xpub = tatum_Request.Generate_XDC_Wallet(Seed,API_KEY,form="Text") - - print(xpub) - print(tatum_Request.Generate_XDC_Wallet_EPK(API_KEY,xpub,index=0)) - print(tatum_Request.Generate_XDC_Private_key(API_KEY,Seed,form="Text")) - print(tatum_Request.Web3_HTTP_Driver(API_KEY,form="Text")) - print(tatum_Request.Current_Block_Number(API_KEY,form="Text")) - print(tatum_Request.XDC_Block_by_Hash(API_KEY,Hash,form="Text")) - print(tatum_Request.XDC_Account_Balance(API_KEY,Address,form="Text")) - blockHash,blockNumber,From,gas,gasPrice,input,nonce,To,transactionIndex,value,contractAddress,cumulativeGasUsed,gasUsed,logs = tatum_Request.XDC_Transaction(API_KEY,Hash,form="Text") - - print(tatum_Request.Count_Outgoing_XDC_Transactions(API_KEY,Address,form="Text")) - - #print(tatum_Request.Send_XDC_ERC20(API_KEY,form="Text")) - #print(tatum_Request.Estimate_XDC_Transaction_Fees(API_KEY,form="Text")) - - print(blockNumber) -if __name__ == "__main__": - Test() diff --git a/LICENCE.txt b/LICENCE.txt new file mode 100644 index 0000000..1ef92da --- /dev/null +++ b/LICENCE.txt @@ -0,0 +1,7 @@ +Copyright © 2022 XDC Foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..e5bb1bf --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1 @@ +global-include *.txt *.py *.md \ No newline at end of file diff --git a/README.md b/README.md index 7f1b98b..ebd8600 100644 --- a/README.md +++ b/README.md @@ -1,234 +1,77 @@ -# **XDC Python SDK V1.0** +# XDC3PYTHON -### **Summary:** +XDC3PYTHON SDK with support for smart contracts, XDC20 & XRC721. -This is a Python SDK for XinFin API published by Quincy@xinfin.org -##### **Haxidecimal Outputs** +## Usage -All hexadecimal need to be converted into **integers** +**pip install XDC3PYTHON** -##### **JSON Schema** +### This SDK supports following Read & Write operations:- -- By default all functions output in JSON so i implemeted a simplified output for variable just place class(form = "Text") for vatiabble output as string | Default output "JSON" +* xrc20 methods. + * Read methods. + * name(), balanceOf(account), totalSupply(), symbol(), decimals(), allowance(pwner, spender). -- The JSON Schema outputed by all the functions is this: - -```json -{ - "jsonrpc":"2.0", - "id":1, - "result":EXAMPLE_RESULT -} -``` - ------- - - - -## **web3** - -#### **POST /clientVersion** - -```python -Version = web3_Request.clientVersion() -print(Version) -##Output {"jsonrpc":"2.0","id":67,"result":"50"} -``` - -Returns the current client version. - -**Parameters** - -**form** = "Text" for varriabled output as string | Default output "JSON" - -**Returns** - -`String` - The current client version - -#### **POST /sha3** - -```python -import hashlib -String= "Q" -Hash = hashlib.sha256(String.encode('utf-8')).hexdigest() - -print(web3_Request.sha3(Hash=Hash,form="Text")) -##Output 0x6d1223fcb20bababbf18827dbe3ac76b13f03e2......... -``` - -Returns Keccak-256 (not the standardized SHA3-256) of the given data. - -**Parameters** - -​ **form** = "Text" for vatiabble output as string | Default output JSON - -​ **Hash** - the Hash to convert into a SHA3 hash - -**Returns**`DATA` - The SHA3 result of the given string. - -## **net** - -#### **POST /version** - -```python -Version = net_Request.version(form="Text") -print(Version) -##Output 50 -``` - -Returns the current network id. - -**Parameters** - -none - -**Returns** - -- `String` - The current network id. - - `"50"`: XinFin Mainnet - - `"89"`: XinFin Testnet - -#### **POST /listening** - -```python -Listening = net_Request.listening(form="Text") -print(Listening) -##Output True -``` - -Returns `true` if client is actively listening for network connections. - -**Parameters** - -none - -**Returns** - -- `Boolean` - `true` when listening, otherwise `false`. + * Write methods. + * transferXDC(owner,receiver), approve(spender,amount), transferToken(receiver,amount), increaseAllowance(spender, addedValue), decreaseAllowance(spender, subtractedValue), transferFrom(sender, receiver, amount). +* xrc721 methods. + * Read methods. + * name(), symbol(), totalsupply(), balanceOf(ownerAddr), ownerOf(tokenId), tokenURI(tokenId), tokenByIndex(index), tokenOfOwnerByIndex(ownerAddress,index), supportInterface(interfaceId), getApproved(tokenId), isApprovedForAll(ownerAddress,spenderAddress). + * Write methods. + * setApprovalForAll(spenderAddress, booleanValue), approve(sepnderAddress , tokenId), transferFrom(recipient, tokenId), safeTransferFrom(spender, tokenId). -#### **POST /peerCount** -```python -Peer = net_Request.peerCount(form="Text") -print(Peer) -##Output 0x8 -``` - -Returns number of peers currently connected to the client. - -**Parameters** - -none - -**Returns** - -- `QUANTITY` - integer of the number of connected peers. - - - -## **eth** - -#### **POST /protocolVersion** +### Example for XRC20. -```python -ETH_Version = eth_Request.protocolVersion(form="Text") -print(int(ETH_Version,16) -##Output 63 -``` - -Returns the current ethereum protocol version. - -**Parameters** - -none - -**Returns** -- `String` - The current ethereum protocol version - - - -#### **POST /syncing** - -```python -Sync = eth_Request.syncing(form="Text") -print(Sync) -##Output False ``` +from XDC3PYTHON.xrc20 import XRC20 -Returns an object with data about the sync status or false. - -**Parameters** +if __name__=="__main__": -none + NETWORK_URL = "Your endpoint Url" -**Returns** + obj = XRC20(NETWORK_URL) -- `Object|Boolean`, An object with sync status data or FALSE, when not syncing: - - `startingBlock`: `QUANTITY` - The block at which the import started (will only be reset, after the sync reached his head) - - `currentBlock`: `QUANTITY` - The current block, same as eth_blockNumber - - `highestBlock`: `QUANTITY` - The estimated highest block - - - -#### **POST /coinbase** - -```python -coinbase = eth_Request.coinbase(form="Text") -print(coinbase) -##Output xdc3056a8bff9a17b12d08f1837d0b44cf1e2018fbe + tokenAddr = input('Enter Token Address: ') + + tokenSymbol = obj.name(tokenAddr) + print(tokenSymbol) ``` -Returns the client coinbase address. **Parameters** none **Returns** - -- `DATA`, 20 bytes - the current coinbase address. +This example returns name of the specified address. +### Example for XRC721. - -#### **POST /gasPrice** - -```python -gasPrice = eth_Request.gasPrice(form="Text") -print(gasPrice) -##Output 0x9c4 ``` +from XDC3PYTHON.xrc721 import XRC721 -Returns the current price per gas in wei. **Parameters** none **Returns** - -- `QUANTITY` - integer of the current gas price in wei. +if __name__=="__main__": + NETWORK_URL = "Your endpoint Url" + obj = XRC721(NETWORK_URL) -#### **POST /accounts** - -``` -POST /accounts + tokenAddr = input('Enter Token Address: ') + + tokenSymbol = obj.name(tokenAddr) + print(tokenSymbol) ``` -Returns a list of addresses owned by client. - -**Parameters** - -none - -**Returns** - -- `Array of DATA`, 20 Bytes - addresses owned by the client - - - -#### **POST /blockNumber** - -``` -POST /blockNumber -``` +This example returns symbol of the specified address. -Returns the number of most recent block. **Parameters** none **Returns** +# Transports -- `QUANTITY` - integer of the current block number the client is on. +**HTTP transport** +## Required Data Types + **Token Address** - `str type` + **Account Address** - `str type` + **amount** & **tokenId** - `int type` +### Author +[XDCFoundation](https://github.com/XDCFoundation/XDC_Python_SDK_V1) diff --git a/XDC3PYTHON/__init__.py b/XDC3PYTHON/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/XDC3PYTHON/createAccount.py b/XDC3PYTHON/createAccount.py new file mode 100644 index 0000000..c3d01c6 --- /dev/null +++ b/XDC3PYTHON/createAccount.py @@ -0,0 +1,9 @@ +from bitcoin import random_key + + + +# Gets private key of wallet to create new account. + +def createAccount(): + privateKey = random_key() + return privateKey \ No newline at end of file diff --git a/XDC3PYTHON/xrc20.py b/XDC3PYTHON/xrc20.py new file mode 100644 index 0000000..03fe905 --- /dev/null +++ b/XDC3PYTHON/xrc20.py @@ -0,0 +1,318 @@ +from web3 import Web3 +from web3._utils.encoding import ( + hexstr_if_str, + to_bytes, +) + +# xrc20 abi.json +xrc20abi = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"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\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"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\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"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\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"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\"}]" + + +# This is a class which consists all the methods as per XRC20 standards. + +class XRC20: + + def __init__(self,rpcUrl): + self.rpcUrl = rpcUrl + + # connection to network. + + def getConnection(self): + w3 = Web3(Web3.HTTPProvider(self.rpcUrl)) + return w3 + + # get contract Instance. + + def getContractInstance(self, tokenAddr): + contractInstance = self.getConnection().eth.contract(address=tokenAddr, abi=xrc20abi) + return contractInstance + + # Gets the Name of the specified address. + # Token address is required as argument. + + def name(self, tokenAddr): + name = self.getContractInstance(tokenAddr).functions.name().call() + return name + + # Gets method returns total supply of token. + # Token address is required as argument. + + def totalSupply(self, tokenAddr): + totalSupply = self.getContractInstance(tokenAddr).functions.totalSupply().call() + totalSupply = self.getConnection().fromWei(totalSupply, 'ether') + return totalSupply + + # Gets the Decimal of the specified address. + # Token address is required as argument. + + def decimal(self, tokenAddr): + decimal = self.getContractInstance(tokenAddr).functions.decimals().call() + return decimal + + # Gets the Symbol of the specified address. + # Token address is required as argument. + + def symbol(self, tokenAddr): + symbol = self.getContractInstance(tokenAddr).functions.symbol().call() + return symbol + + # Gets the balance of the specified address. + # token address, owner address are required as arguments. + + def balanceOf(self, tokenAddr, ownerAddress): + owner = Web3.toChecksumAddress(ownerAddress) + balance = self.getContractInstance(tokenAddr).functions.balanceOf(owner).call() + return self.getConnection().fromWei(balance, 'ether') + + # This method returns how much allowance spender have from owner. + # This function required three arguments. + # owner address, spender address, token address. + + def allowance(self, tokenAddr, ownerAddress, spenderAddress): + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(spenderAddress) + Allowance = self.getContractInstance(tokenAddr).functions.allowance(owner, spender).call() + return self.getConnection().fromWei(Allowance, 'ether') + + # Transfer XDC for a specified address. + # This function requires following arguments. + # private key, recipient address, amount. + + def transferXDC(self, ownerAddress, receiverAddress, ownerPrivateKey, amount): + + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(receiverAddress) + amount = self.getConnection().toWei(amount, 'ether') + + nonce = self.getConnection().eth.getTransactionCount(owner) + gasPrice = self.getConnection().eth.gas_price + estimateGas = self.getConnection().eth.estimateGas({ + 'to': spender, + 'from': owner, + 'value': amount + }) + + tx = { + 'nonce': nonce, + 'to': spender, + 'value': amount, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + + signedTx = self.getConnection().eth.account.signTransaction(tx, ownerPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) + + # Transfer token for a specified address. + # This function requires following arguments. + # ownerAddress, ownerPrivateKey, receiver address, token address, amount. + + def transferToken(self, tokenAddr, ownerAddress, ownerPrivateKey, receiverAddress, amount): + + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(receiverAddress) + + balance = self.balanceOf(tokenAddr,owner) + + if amount > balance: + return "amount exceeds balance" + + amount = self.getConnection().toWei(amount, 'ether') + + Transfer = self.getContractInstance(tokenAddr).functions.transfer(spender, amount) + + hexData = Transfer._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + estimateGas = Transfer.estimateGas( + { + 'from': owner, + } + ) + + nonce = self.getConnection().eth.getTransactionCount(owner) + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + + signedTx = self.getConnection().eth.account.signTransaction(tx, ownerPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) + + # Approve the passed address to spend the specified amount of tokens on behalf of owner. + # This function required arguments. + # ownerAddress, ownerPrivateKey, spenderAddress, tokenAddr, amount. + + def approve(self, tokenAddr, ownerAddress, ownerPrivateKey, spenderAddress, amount): + + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(spenderAddress) + + balance = self.balanceOf(tokenAddr, owner) + allowanceAmount = self.allowance(tokenAddr, owner, spender) + + if amount > balance and allowanceAmount > balance: + return "amount exceeds balance" + + amount = self.getConnection().toWei(amount, 'ether') + + approveData = self.getContractInstance(tokenAddr).functions.approve(spender, amount) + + hexData = approveData._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + estimateGas = approveData.estimateGas() + + nonce = self.getConnection().eth.getTransactionCount(owner) + + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + + signedTx = self.getConnection().eth.account.signTransaction(tx, ownerPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) + + # increase the amount of tokens that an owner allowed to a spender. + # This function required arguments. + # owner address, ownerPrivateKey, spender address, token address, amount. + + def increaseAllowance(self, tokenAddr, ownerAddress, ownerPrivateKey, spenderAddress, amount): + + + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(spenderAddress) + + balance = self.balanceOf(tokenAddr, owner) + + allowanceAmount = self.allowance(tokenAddr, owner , spender) + + allowanceAmount = self.getConnection().fromWei(allowanceAmount, 'ether') + + totalAmount = allowanceAmount + amount + + if totalAmount > balance: + return "amount exceeds balance" + + totalAmount = self.getConnection().toWei(totalAmount, 'ether') + + Transfer = self.getContractInstance(tokenAddr).functions.approve(spender, totalAmount) + + hexData = Transfer._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + estimateGas = Transfer.estimateGas() + + nonce = self.getConnection().eth.getTransactionCount(owner) + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + signedTx = self.getConnection().eth.account.signTransaction(tx, ownerPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) + + # decrease the amount of tokens that an owner allowed to a spender. + # This function required arguments. + # owner address, ownerPrivateKey, spender address, token address, amount. + + def decreaseAllowance(self, tokenAddr, ownerAddress, ownerPrivateKey, spenderAddress, amount): + + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(spenderAddress) + + allowanceAmount = self.allowance(tokenAddr, owner, spender) + allowanceAmount = self.getConnection().fromWei(allowanceAmount, 'ether') + + if allowanceAmount >= amount: + totalAmount = allowanceAmount - amount + else: + totalAmount = amount - allowanceAmount + + totalAmount = self.getConnection().toWei(totalAmount, 'ether') + + approveData = self.getContractInstance(tokenAddr).functions.approve(spender, totalAmount) + + hexData = approveData._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + estimateGas = approveData.estimateGas() + + nonce = self.getConnection().eth.getTransactionCount(owner) + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + signedTx = self.getConnection().eth.account.signTransaction(tx, ownerPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) + + # Transfer tokens from one address to another. + # This function requires following arguments. + # owner address, spenderPrivateKey, spender address, receiver address, token address, amount. + + def transferFrom(self, tokenAddr, ownerAddress, spenderPrivateKey, spenderAddress, receiver, amount): + + owner = Web3.toChecksumAddress(ownerAddress) + receiverAddres = Web3.toChecksumAddress(receiver) + spender = Web3.toChecksumAddress(spenderAddress) + + amount = self.getConnection().toWei(amount, 'ether') + + transferData = self.getContractInstance(tokenAddr).functions.transferFrom( + owner, receiverAddres, amount) + + estimateGas = transferData.estimateGas({ + 'from': spender, + }) + + hexData = transferData._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + nonce = self.getConnection().eth.getTransactionCount(spender) + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + signedTx = self.getConnection().eth.account.signTransaction(tx, spenderPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) diff --git a/XDC3PYTHON/xrc721.py b/XDC3PYTHON/xrc721.py new file mode 100644 index 0000000..2740422 --- /dev/null +++ b/XDC3PYTHON/xrc721.py @@ -0,0 +1,281 @@ +from web3 import Web3 +from web3._utils.encoding import ( + hexstr_if_str, + to_bytes, +) + + +# xrc721 abi.json +xrc721abi = "[{\"constant\":true,\"inputs\":[{\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"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\":\"from\",\"type\":\"address\"},{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"},{\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"owner\",\"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\":\"to\",\"type\":\"address\"},{\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"},{\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom1\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_uri\",\"type\":\"string\"}],\"name\":\"mint\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"},{\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"operator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"}]" + + +# This is a class which consists all the methods as per XRC721 standards. + +class XRC721: + + def __init__(self,rpcUrl): + self.rpcUrl = rpcUrl + + # connection to network. + + def getConnection(self): + w3 = Web3(Web3.HTTPProvider(self.rpcUrl)) + return w3 + + # get contract Instance. + + def getContractInstance(self, tokenAddr): + contractInstance = self.getConnection().eth.contract(address=tokenAddr, abi=xrc721abi) + return contractInstance + + # Gets the Name of the specified address. + # token address required as an argument. + + def name(self, tokenAddr): + result = self.getContractInstance(tokenAddr).functions.name().call() + return result + + # Gets the Symbol of the specified address. + # token address required as an argument. + + def symbol(self, tokenAddr): + result = self.getContractInstance(tokenAddr).functions.symbol().call() + return result + + # Gets the owner of an NFT. + # required arguments. + # token address, token id. + + def ownerOf(self, tokenAddr, tokenId): + result = self.getContractInstance(tokenAddr).functions.ownerOf(tokenId).call() + return result + + # Gets the Totalsupply of the specified address. + # token address required as an argument. + + def totalSupply(self, tokenAddr): + token = Web3.toChecksumAddress(tokenAddr) + result = self.getContractInstance(tokenAddr).functions.totalSupply().call() + resultt = str(result) + return resultt + + # Gets the balance of the specified address. + # reuired arguments + # token address, owner address. + + def balanceOf(self, tokenAddr, ownerAddress): + owner = Web3.toChecksumAddress(ownerAddress) + result = self.getContractInstance(tokenAddr).functions.balanceOf(owner).call() + return result + + # A distinct Uniform Resource Identifier (URI) for a given asset. + # Gets URI of a token. + # required arguments + # tokenId The identifier for an NFT. + # address of the token. + + def tokenURI(self, tokenAddr, tokenId): + result = self.getContractInstance(tokenAddr).functions.tokenURI(tokenId).call() + return result + + # Enumerate NFTs assigned to an owner. + # tokenAddress An address for whom to query. + # IndexNO A counter less than `totalSupply()`. + # The token identifier for the `index`th NFT assigned to `owner`. + + def tokenByIndex(self, tokenAddr, index): + token = Web3.toChecksumAddress(tokenAddr) + result = self.getContractInstance(tokenAddr).functions.tokenByIndex(index).call() + return result + + # Enumerate NFTs assigned to an owner. + # The token identifier for the `index`th NFT assigned to `owner`. + # required arguments. + # owner address, token address, token index. + + def tokenofOwnerByIndex(self, tokenAddr, ownerAddress, index): + token = Web3.toChecksumAddress(tokenAddr) + owner = Web3.toChecksumAddress(ownerAddress) + result = self.getContractInstance(token).functions.tokenOfOwnerByIndex( + owner, index).call() + return result + + # Query if a contract implements an interface. + # tokenAddress An address for whom to query and x_bytes The interface identifier. + # `true` if the contract implements `interfaceID` andinterfaceID` is not 0xffffffff, `false` otherwise. + # required arguments. + # token address, interface id. + + def supportInterface(self, tokenAddr, interfaceId): + token = Web3.toChecksumAddress(tokenAddr) + result = self.getContractInstance(token).functions.supportsInterface( + interfaceId).call() + return result + + # The approved address for a token ID, or zero if no address set Reverts if the token ID does not exist. + # required arguments. + # token address, tokenId. + + def getApproved(self, tokenAddr, tokenId): + result = self.getContractInstance(tokenAddr).functions.getApproved(tokenId).call() + return result + + # Tells whether an operator is approved by a given owner. + # required arguments. + # owner address, spender address, token address. + + def isApprovedForAll(self, tokenAddr, ownerAddress, spenderAddress): + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(spenderAddress) + result = self.getContractInstance(tokenAddr).functions.isApprovedForAll( + owner, spender).call() + return result + + # Change or reaffirm the approved address for an NFT. + # The zero address indicates there is no approved address. + # Throws unless `owner` is the current NFT owner, or an authorized. + # required arguments. + # tokenAddress, owner address, ownerPrivateKey, spenderAddress, tokenID. + + def approve(self, tokenAddr, ownerAddress, ownerPrivateKey, spenderAddress, tokenId): + + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(spenderAddress) + + approveData = self.getContractInstance(tokenAddr).functions.approve(spender, tokenId) + + hexData = approveData._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + estimateGas = approveData.estimateGas({ + 'from': owner, + }) + + nonce = self.getConnection().eth.getTransactionCount(owner) + + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + + signedTx = self.getConnection().eth.account.signTransaction(tx, ownerPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) + + # Enable or disable approval for a third party ("operator") to manage all of `Owner`'s assets + # Emits the ApprovalForAll event. The contract MUST allow multiple operators per owner. + # required arguments. + # token address, owner address, ownerPrivateKey, sepnder address, tokenId. + + def setApprovalForAll(self, tokenAddr, ownerAddress, ownerPrivateKey, spenderAddress, boolValue): + + owner = Web3.toChecksumAddress(ownerAddress) + spender = Web3.toChecksumAddress(spenderAddress) + + approveData = self.getContractInstance(tokenAddr).functions.setApprovalForAll( + spender, boolValue) + + hexData = approveData._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + estimateGas = approveData.estimateGas({ + 'from': owner, + }) + + nonce = self.getConnection().eth.getTransactionCount(owner) + + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + + signedTx = self.getConnection().eth.account.signTransaction(tx, ownerPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) + + # Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE + # to confirm that `reciever Address` is capable of receiving NFTs or else they may be permanently lost. + # required arguments. + # token address, owner address, spender address, spenderPrivateKey, receiver address, tokenId. + + def transferFrom(self, tokenAddr, ownerAddress, spenderAddress, spenderPrivateKey, receiver, tokenId): + + owner = Web3.toChecksumAddress(ownerAddress) + receiverAddres = Web3.toChecksumAddress(receiver) + spender = Web3.toChecksumAddress(spenderAddress) + + transferData = self.getContractInstance(tokenAddr).functions.transferFrom( + owner, receiverAddres, tokenId) + + estimateGas = transferData.estimateGas({ + 'from': spender, + }) + + hexData = transferData._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + nonce = self.getConnection().eth.getTransactionCount(spender) + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + signedTx = self.getConnection().eth.account.signTransaction(tx, spenderPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) + + # Transfers the ownership of an NFT from one address to another address. + # required arguments. + # token address, owner address, spender address, spenderPrivateKey, receiver address, tokenId. + + def safeTransferFrom(self, tokenAddr, ownerAddress, spenderAddress, spenderPrivateKey, receiver, tokenId): + + owner = Web3.toChecksumAddress(ownerAddress) + receiverAddres = Web3.toChecksumAddress(receiver) + spender = Web3.toChecksumAddress(spenderAddress) + + transferData = self.getContractInstance(tokenAddr).functions.safeTransferFrom( + owner, receiverAddres, tokenId) + + estimateGas = transferData.estimateGas({ + 'from': spender, + }) + + hexData = transferData._encode_transaction_data() + + data = hexstr_if_str(to_bytes, hexData) + + nonce = self.getConnection().eth.getTransactionCount(spender) + gasPrice = self.getConnection().eth.gas_price + + tx = { + 'nonce': nonce, + 'to': tokenAddr, + 'data': data, + 'gas': estimateGas, + 'gasPrice': gasPrice, + } + signedTx = self.getConnection().eth.account.signTransaction(tx, spenderPrivateKey) + + txHash = self.getConnection().eth.sendRawTransaction(signedTx.rawTransaction) + return self.getConnection().toHex(txHash) diff --git a/__pycache__/Base_API_Call.cpython-37.pyc b/__pycache__/Base_API_Call.cpython-37.pyc deleted file mode 100644 index 82704d8..0000000 Binary files a/__pycache__/Base_API_Call.cpython-37.pyc and /dev/null differ diff --git a/__pycache__/Base_API_Call.cpython-39.pyc b/__pycache__/Base_API_Call.cpython-39.pyc deleted file mode 100644 index 62ca0b1..0000000 Binary files a/__pycache__/Base_API_Call.cpython-39.pyc and /dev/null differ diff --git a/__pycache__/eth.cpython-39.pyc b/__pycache__/eth.cpython-39.pyc deleted file mode 100644 index dfeaf50..0000000 Binary files a/__pycache__/eth.cpython-39.pyc and /dev/null differ diff --git a/__pycache__/net.cpython-39.pyc b/__pycache__/net.cpython-39.pyc deleted file mode 100644 index 5ca6a8e..0000000 Binary files a/__pycache__/net.cpython-39.pyc and /dev/null differ diff --git a/__pycache__/tatum.cpython-39.pyc b/__pycache__/tatum.cpython-39.pyc deleted file mode 100644 index 2c5f65e..0000000 Binary files a/__pycache__/tatum.cpython-39.pyc and /dev/null differ diff --git a/__pycache__/web3.cpython-37.pyc b/__pycache__/web3.cpython-37.pyc deleted file mode 100644 index 611f851..0000000 Binary files a/__pycache__/web3.cpython-37.pyc and /dev/null differ diff --git a/__pycache__/web3.cpython-39.pyc b/__pycache__/web3.cpython-39.pyc deleted file mode 100644 index 2de66dd..0000000 Binary files a/__pycache__/web3.cpython-39.pyc and /dev/null differ diff --git a/eth.py b/eth.py deleted file mode 100644 index b35f1f5..0000000 --- a/eth.py +++ /dev/null @@ -1,213 +0,0 @@ -from Base_API_Call import API -import http.client -import json - -class eth_Request: - def protocolVersion(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//protocolVersion" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_protocolVersion\",\"params\":[],\"id\":67}" - - return API.Format(Call,Payload,Content,conn,form) - - def syncing(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//syncing" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_syncing\",\"params\":[],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def coinbase(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//coinbase" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_coinbase\",\"params\":[],\"id\":64}" - - return API.Format(Call,Payload,Content,conn,form) - - def gasPrice(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//gasPrice" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_gasPrice\",\"params\":[],\"id\":73}" - - return API.Format(Call,Payload,Content,conn,form) - - def accounts(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON",ETH_account="0x438e0b511981FE8CF7283e981ca8c3394bB3646E"): - Call = "POST" - Content = "//accounts" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_accounts\",\"params\":[%s],\"id\":1}" % ETH_account - - return API.Format(Call,Payload,Content,conn,form) - - def blockNumber(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//blockNumber" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":83}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBalance(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON",Address=""): - Call = "POST" - Content = "//getBalance" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBalance\",\"params\":[\"xdce4C4FeBE1Cb34C3490167c163C9ED92049B32B5c\",\"latest\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - -#### REVIEW #### - def getStorageAt(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getStorageAt" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getStorageAt\",\"params\":[\"0x295a70b2de5e3953354a6a8344e616ed314d7251\",\"0x0\",\"latest\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) -#### #### #### #### - def getTransactionCount(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getTransactionCount" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\",\"params\":[\"0xbf1dcb735e512b731abd3404c15df6431bd03d42\",\"latest\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBlockTransactionCountByHash(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getBlockTransactionCountByHash" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockTransactionCountByHash\",\"params\":[\"0xc8b967161c671ce952a3d50987a78d64157fb5a8e1724804b87d3e9b11e3aa34\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBlockTransactionCountByNumber(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getBlockTransactionCountByNumber" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockTransactionCountByNumber\",\"params\":[\"0x52A8CA\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getCode(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getCode" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getCode\",\"params\":[\"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b\",\"0x2\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - -#### REVIEW #### - def sign(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//sign" - Payload = "{ \"jsonrpc\": \"2.0\", \"method\": \"eth_accounts\", \"params\": [], \"id\": 1}" - - return API.Format(Call,Payload,Content,conn,form) -#### #### #### #### - - def sendTransaction(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//sendTransaction" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"to\":\"0xd46e8dd67c5d32be8058bb8eb970870f07244567\",\"gas\":\"0x76c0\",\"gasPrice\":\"0x9184e72a000\",\"value\":\"0x9184e72a\",\"data\":\"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675\"}],\"id\":1}" - - - return API.Format(Call,Payload,Content,conn,form) - - def sendRawTransaction(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//sendRawTransaction" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_sendRawTransaction\",\"params\":[\"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def call(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//call" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_call\",\"params\":[{\"from\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"to\":\"0xd46e8dd67c5d32be8058bb8eb970870f07244567\",\"gas\":\"0x76c0\",\"gasPrice\":\"0x9184e72a000\",\"value\":\"0x9184e72a\",\"data\":\"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675\"},\"latest\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def estimateGas(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//estimateGas" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"to\":\"0xd46e8dd67c5d32be8058bb8eb970870f07244567\",\"gas\":\"0x76c0\",\"gasPrice\":\"0x9184e72a000\",\"value\":\"0x9184e72a\",\"data\":\"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675\"}],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBlockByHash(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getBlockByHash" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByHash\",\"params\":[\"0x9326145f8a2c8c00bbe13afc7d7f3d9c868b5ef39d89f2f4e9390e9720298624\",true],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBlockByNumber(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getBlockByNumber" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\",\"params\":[\"0x0\",true],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBlockSignersByNumber(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getBlockSignersByNumber" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockSignersByNumber\",\"params\":[\"0xA61F98\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBlockSignersByHash(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getBlockSignersByHash" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockSignersByHash\",\"params\":[\"0x605777ee60ef3ccf21e079fa1b091b0196cf1a2c1dd7c088dd5b1ab03f680b6f\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBlockFinalityByNumber(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getBlockFinalityByNumber" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockFinalityByNumber\",\"params\":[\"0xA61F98\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getBlockFinalityByHash(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getBlockFinalityByHash" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockFinalityByHash\",\"params\":[\"0x605777ee60ef3ccf21e079fa1b091b0196cf1a2c1dd7c088dd5b1ab03f680b6f\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getCandidates(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getCandidates" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getCandidates\",\"params\":[\"latest\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getCandidateStatus(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getCandidateStatus" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getCandidateStatus\",\"params\":[\"0x1d50df657b6dce50bac634bf18e2d986d807e940\",\"latest\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getTransactionByHash(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getTransactionByHash" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionByHash\",\"params\":[\"0xd83b26e101dd6480764bade90fc283407919f60b7e65ff83fbf6cdc92f1138a1\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getTransactionByBlockHashAndIndex(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getTransactionByBlockHashAndIndex" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionByBlockHashAndIndex\",\"params\":[\"0x3c82bc62179602b67318c013c10f99011037c49cba84e31ffe6e465a21c521a7\",\"0x0\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getTransactionByBlockNumberAndIndex(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getTransactionByBlockNumberAndIndex" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionByBlockNumberAndIndex\",\"params\":[\"0x52A96E\",\"0x1\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - def getTransactionReceipt(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//getTransactionReceipt" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionReceipt\",\"params\":[\"0xa3ece39ae137617669c6933b7578b94e705e765683f260fcfe30eaa41932610f\"],\"id\":1}" - - return API.Format(Call,Payload,Content,conn,form) - - diff --git a/net.py b/net.py deleted file mode 100644 index 8185df2..0000000 --- a/net.py +++ /dev/null @@ -1,27 +0,0 @@ -from Base_API_Call import API -import http.client -import json - -class net_Request: - def version(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//version" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"net_version\",\"params\":[],\"id\":67}" - - return API.Format(Call,Payload,Content,conn,form) - - def listening(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//listening" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"net_listening\",\"params\":[],\"id\":67}" - - return API.Format(Call,Payload,Content,conn,form) - - def peerCount(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//peerCount" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"net_peerCount\",\"params\":[],\"id\":74}" - - return API.Format(Call,Payload,Content,conn,form) - - diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..28e3abe --- /dev/null +++ b/setup.py @@ -0,0 +1,15 @@ +from setuptools import setup, find_packages + + + +setup( + name = 'XDC3PYTHON', + version = '1.0.1', + description = 'XDC PYTHON SDK with support for smart contracts, XRC20 & XRC721', + long_description=open('README.md').read(), + url='https://github.com/XDCFoundation/XDC_Python_SDK_V1.git', + author='XDC Foundation', + license='MIT', + keywords='', + packages=find_packages(), +) \ No newline at end of file diff --git a/tatum.py b/tatum.py deleted file mode 100644 index 2a2a43a..0000000 --- a/tatum.py +++ /dev/null @@ -1,195 +0,0 @@ -from Base_API_Call import API -import http.client -import json - -conn = http.client.HTTPSConnection("api-eu1.tatum.io") - -class tatum_Request(): - def Generate_XDC_Wallet(Seed, API_KEY,form="JSON"): - headers = { 'x-api-key': API_KEY } - conn.request("GET", "/v3/xdc/wallet?mnemonic=%s" % Seed, headers=headers) - - res = conn.getresponse() - data = res.read() - - if form == "JSON": - return data.decode("utf-8") - else: - DATA = data.decode("utf-8") - Item = json.loads(DATA) - - xpub = Item["xpub"] - mnemonic =Item["mnemonic"] - - return xpub - -############ TEST ############ - def Generate_XDC_Wallet_EPK(API_KEY,xpub,index,form="JSON"): - headers = { 'x-api-key': API_KEY } - conn.request("GET", "/v3/xdc/address/%s/%s" % (xpub,index), headers=headers) - res = conn.getresponse() - data = res.read() - - if form == "JSON": - return data.decode("utf-8") - else: - DATA = data.decode("utf-8") - Item = json.loads(DATA) - address = Item["address"] - - return address - - def Generate_XDC_Private_key(API_KEY,Seed,form="JSON"): - payload = "{\"index\":0,\"mnemonic\":\"%s\"}" % Seed - headers = { - 'content-type': "application/json", - 'x-api-key': API_KEY - } - - conn.request("POST", "/v3/xdc/wallet/priv", payload, headers) - res = conn.getresponse() - data = res.read() - - if form == "JSON": - return data.decode("utf-8") - else: - DATA = data.decode("utf-8") - Item = json.loads(DATA) - key = Item["key"] - - return key - - def Web3_HTTP_Driver(ApiKey,form="JSON"): - Call = "POST" - Content = "/v3/xdc/web3/%s" % ApiKey - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"web3_clientVersion\",\"params\":[],\"id\":2}" - - return API.Format(Call,Payload,Content,conn,form) - - def Current_Block_Number(API_Key,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - headers = { 'x-api-key': API_Key } - conn.request("GET", "/v3/xdc/block/current", headers=headers) - res = conn.getresponse() - data = res.read() - - return (data.decode("utf-8")) - -####### TEST ####### - def XDC_Block_by_Hash(API_KEY,Hash,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - headers = { 'x-api-key': API_KEY } - conn.request("GET", "/v3/xdc/block/%s" % Hash, headers=headers) - res = conn.getresponse() - data = res.read() - - return (data.decode("utf-8")) - - def XDC_Account_Balance(API_KEY,Address,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - headers = { 'x-api-key': API_KEY } - conn.request("GET", "/v3/xdc/account/balance/%s" % Address, headers=headers) - res = conn.getresponse() - data = res.read() - - if form == "Text": - Item = json.loads(data.decode("utf-8")) - balance = Item["balance"] - return balance - else: - return (data.decode("utf-8")) - - def XDC_Transaction(API_KEY,Hash,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - headers = { 'x-api-key': API_KEY } - conn.request("GET", "/v3/xdc/transaction/%s" % Hash, headers=headers) - res = conn.getresponse() - data = res.read() - - if form == "Text": - Item = json.loads(data.decode("utf-8")) - blockHash = Item["blockHash"] - blockNumber = Item["blockNumber"] - From = Item["from"] - gas = Item["gas"] - gasPrice = Item["gasPrice"] - input = Item["input"] - nonce = Item["nonce"] - To = Item["to"] - transactionIndex = Item["transactionIndex"] - value = Item["value"] - contractAddress = Item["contractAddress"] - cumulativeGasUsed = Item["cumulativeGasUsed"] - gasUsed = Item["gasUsed"] - logs = Item["logs"] - - return [blockHash,blockNumber,From,gas,gasPrice,input,nonce,To,transactionIndex,value,contractAddress,cumulativeGasUsed,gasUsed,logs] - else: - return (data.decode("utf-8")) - - def Count_Outgoing_XDC_Transactions(API_KEY,Address,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - headers = { 'x-api-key': API_KEY } - conn.request("GET", "/v3/xdc/transaction/count/%s" % Address, headers=headers) - res = conn.getresponse() - data = res.read() - - return data.decode("utf-8") - -####### TEST ####### - def Send_XDC_ERC20(API_KEY,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - payload = "{\"data\":\"My note to recipient.\",\"nonce\":0,\"to\":\"xdc687422eEA2cB73B5d3e242bA5456b782919AFc85\",\"fee\":{\"gasLimit\":\"40000\",\"gasPrice\":\"20\"},\"amount\":\"100000\",\"fromPrivateKey\":\"0x05e150c73f1920ec14caa1e0b6aa09940899678051a78542840c2668ce5080c2\"}" - headers = { - 'content-type': "application/json", - 'x-api-key': API_KEY - } - conn.request("POST", "/v3/xdc/transaction", payload, headers) - res = conn.getresponse() - data = res.read() - - return data.decode("utf-8") - -####### TEST ####### - def Estimate_XDC_Transaction_Fees(API_KEY,Address1,Address2,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - payload = "{\"from\":\"xdcfb99f8ae9b70a0c8cd96ae665bbaf85a7e01a2ef\",\"to\":\"xdc687422eEA2cB73B5d3e242bA5456b782919AFc85\",\"amount\":\"100000\",\"data\":\"My note to recipient.\"}" - headers = { - 'content-type': "application/json", - 'x-api-key': API_KEY - } - conn.request("POST", "/v3/xdc/gas", payload, headers) - res = conn.getresponse() - data = res.read() - - return data.decode("utf-8") - -####### TEST ####### - def Execute_Smart_Contract(API_KEY,contractAddress,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - payload = "{\"contractAddress\":\"xdc687422eEA2cB73B5d3e242bA5456b782919AFc85\",\"methodName\":\"transfer\",\"methodABI\":{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"stake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},\"params\":[\"0x632\"]}" - headers = { - 'content-type': "application/json", - 'x-api-key': API_KEY - } - - conn.request("POST", "/v3/xdc/smartcontract", payload, headers) - res = conn.getresponse() - data = res.read() - - return (data.decode("utf-8")) - -####### TEST ####### - def Broadcast_Signed_XDC_Transaction(API_KEY,txData,signatureId,form="JSON"): - conn = http.client.HTTPSConnection("api-eu1.tatum.io") - payload = "{\"txData\":\"62BD544D1B9031EFC330A3E855CC3A0D51CA5131455C1AB3BCAC6D243F65460D\",\"signatureId\":\"1f7f7c0c-3906-4aa1-9dfe-4b67c43918f6\"}" - headers = { - 'content-type': "application/json", - 'x-api-key': API_KEY - } - - conn.request("POST", "/v3/xdc/broadcast", payload, headers) - res = conn.getresponse() - data = res.read() - - return (data.decode("utf-8")) diff --git a/web3.py b/web3.py deleted file mode 100644 index 5e69052..0000000 --- a/web3.py +++ /dev/null @@ -1,17 +0,0 @@ -from Base_API_Call import API -import http.client - -class web3_Request: - def clientVersion(conn=http.client.HTTPSConnection("rpc.xinfin.network"), form="JSON"): - Call = "POST" - Content = "//version" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"net_version\",\"params\":[],\"id\":67}" - - return API.Format(Call,Payload,Content,conn,form) - - def sha3(conn=http.client.HTTPSConnection("rpc.xinfin.network"),form ="JSON",Hash=""): - Call = "POST" - Content = "//sha3" - Payload = "{\"jsonrpc\":\"2.0\",\"method\":\"web3_sha3\",\"params\":[\"0x%s\"],\"id\":64}" % Hash - - return API.Format(Call,Payload,Content,conn,form) \ No newline at end of file