Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] TON Access for networking, Stabilize wallet deployment #18

Merged
merged 5 commits into from
Feb 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Rift

[![PyPI version](https://img.shields.io/badge/rift--framework-0.9.14-informational?style=flat-square&color=FFFF91&labelColor=360825)](https://pypi.org/project/rift-framework/)
[![PyPI version](https://img.shields.io/badge/rift--framework-0.10.0-informational?style=flat-square&color=FFFF91&labelColor=360825)](https://pypi.org/project/rift-framework/)
[![Telegram](https://img.shields.io/badge/Telegram-@skyring__org-informational?style=flat-square&color=0088cc&labelColor=360825)](https://t.me/skyring_org)
[![Telegram](https://img.shields.io/badge/Docs-docs.skyring.io/rift-informational?style=flat-square&color=6A0F49&labelColor=360825)](https://docs.skyring.io/rift/)

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "rift-framework"
version = "0.9.14"
version = "0.10.0"
description = "The magical Python -> TON Portal"
authors = ["Amin Rezaei <[email protected]>"]
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion rift/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
from rift.func import *
from rift.library import *
from rift.network import *
from rift.types import *
from rift.runtime import *
from rift.types import *
2 changes: 1 addition & 1 deletion rift/cli/commands/build.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from os import getcwd, path, makedirs
from os import getcwd, makedirs, path

import click

Expand Down
19 changes: 9 additions & 10 deletions rift/cli/commands/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from rift.cli.entry import entry
from rift.fift.types import Cell
from rift.func.meta_contract import ContractMeta
from rift.network.network import Network
from rift.network.v2_network import Network
from rift.runtime.config import FiftMode
from rift.wallet.wallet_manager import WalletManager

Expand Down Expand Up @@ -68,23 +68,22 @@ def deploy(target: str, network: str):
contract.__code_cell__ = code_cell

FiftMode.activate()
res = mod.deploy()

network = network.lower()
n = Network(testnet=network == "test-net")

res = mod.deploy(n)
if isinstance(res, tuple):
msg, independent = res
else:
msg, independent = res, False

network = network.lower()
n = Network(testnet=network == "test-net")

if independent:
# send to blockchain
r = n.send_boc(msg)
else:
# acquire wallet, build msg and then send
r = WalletManager.send_message(n, msg)
if r["ok"]:
print("Successfuly deployed contract at the address:", "")
else:
print("Error deploying contract")
print(r)
if r == -1:
return
print("Successfuly deployed contract at the address")
2 changes: 1 addition & 1 deletion rift/cli/commands/init.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import subprocess
from os.path import join as pjoin

import click

from rift.cli.entry import entry
import subprocess

templates = {
"bare": "https://github.com/sky-ring/rift-bare-template",
Expand Down
2 changes: 1 addition & 1 deletion rift/fift/func.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ def prepare_rstd(cls):
# TODO: is this an ideal place for this func?
if "rstd" in FUNC_LIBS:
return
from rift.library.rstd import RiftLib
from rift.func.engine import Engine
from rift.library.rstd import RiftLib

t = Engine.patched(RiftLib)
compiled = Engine.compile(t)
Expand Down
2 changes: 1 addition & 1 deletion rift/fift/types/cell.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from rift.fift.types._fift_base import _FiftBaseType
from rift.fift.types.factory import Factory
from rift.network.network import Network
from rift.network.v2_network import Network
from rift.util import type_id


Expand Down
1 change: 0 additions & 1 deletion rift/fift/types/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from rift.fift.types._fift_base import _FiftBaseType
from rift.fift.types.cell import Cell
from rift.fift.types.factory import Factory
from rift.network.network import Network
from rift.util import type_id


Expand Down
4 changes: 2 additions & 2 deletions rift/func/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from rift.func.meta_contract import ContractMeta
from rift.func.types.types import Cell, Slice
from rift.func.util import cls_attrs
from rift.network.network import Network
from rift.network.inetwork import INetwork
from rift.types.bases.cell import Cell as GeneralCell
from rift.types.model import Model
from rift.types.msg import (
Expand Down Expand Up @@ -70,7 +70,7 @@ def __getattr__(self, item):

def connect(
self,
network: Network,
network: INetwork,
addr: str,
use_code=False,
use_data=True,
Expand Down
2 changes: 1 addition & 1 deletion rift/network/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
from rift.network.account import Account, AccountState
from rift.network.network import Network
from rift.network.v2_network import Network
3 changes: 3 additions & 0 deletions rift/network/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@ def __init__(self, raw_data=None, addr="") -> None:
self._init_from_raw(raw_data)
if addr != "":
self.addr = addr
self.data = ""
self.code = ""

def _init_from_raw(self, data):
balance = int(data["balance"])
code = data["code"]
c_data = data["data"]
if balance == -1:
balance = 0
state = AccountState.EMPTY
elif code == "" and c_data == "":
state = AccountState.UNINIT
Expand Down
5 changes: 5 additions & 0 deletions rift/network/error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class NetworkError(Exception):
def __init__(self, code, error):
self.code = code
self.error = error
super().__init__(f"{code}: {error}")
11 changes: 11 additions & 0 deletions rift/network/inetwork.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from abc import ABC, abstractmethod


class INetwork(ABC):
@abstractmethod
def send_boc(self):
pass

@abstractmethod
def get_account(self):
pass
34 changes: 34 additions & 0 deletions rift/network/ton_access.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import functools
import json
import random

import requests

EDGE_ENDPOINT = "https://ton.access.orbs.network"
VESRION = 1


@functools.cache
def get_nodes():
nodes_api = f"{EDGE_ENDPOINT}/nodes"
body = requests.get(nodes_api).content
nodes = json.loads(body)
# Filter out unhealthy
nodes = filter(lambda x: x["Healthy"] == "1", nodes)
return list(nodes)


def route(protocol="toncenter-api-v2", testnet=False):
return endpoint(protocol=protocol, testnet=testnet, node_id="route")


def endpoint(protocol="toncenter-api-v2", testnet=False, node_id=None):
if node_id is None:
nodes = get_nodes()
i = random.randint(0, len(nodes) - 1)
node_id = nodes[i]["Name"]
network = "testnet" if testnet else "mainnet"
suffix = ""
return (
f"{EDGE_ENDPOINT}/{node_id}/{VESRION}/{network}/{protocol}/{suffix}"
)
Empty file added rift/network/tonlib/__init__.py
Empty file.
2 changes: 1 addition & 1 deletion rift/network/network.py → rift/network/tonlib/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from rift.logging import log_info, log_panic, log_warn
from rift.network.account import Account
from rift.network.config import ConfigManager
from rift.network.servers import Servers
from rift.network.tonlib.servers import Servers
from rift.runtime.config import Config


Expand Down
File renamed without changes.
62 changes: 62 additions & 0 deletions rift/network/v2_network.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import base64 as b64
from urllib.parse import urlencode

import requests

from rift.network.account import Account, AccountState
from rift.network.error import NetworkError
from rift.network.inetwork import INetwork
from rift.network.ton_access import endpoint as get_endpoint


class Network(INetwork):
def __init__(self, endpoint=None, testnet=False):
if endpoint is None:
endpoint = get_endpoint(testnet=testnet)
if endpoint.endswith("/"):
endpoint = endpoint[:-1]
self.endpoint = endpoint

def execute_get(self, method: str, query=None, **kwargs):
if query is None:
query = {}
query = {**query, **kwargs}
params = urlencode(query)
full_url = f"{self.endpoint}/{method}?{params}"
r = requests.get(full_url)
d = r.json()
if r.status_code != 200:
raise NetworkError(d["code"], d["error"])
return d["result"]

def execute_post(self, method: str, body: dict):
if body is None:
body = {}
full_url = f"{self.endpoint}/{method}"
r = requests.post(full_url, json=body)
d = r.json()
if r.status_code != 200:
raise NetworkError(d["code"], d["error"])
return d["result"]

def send_boc(self, boc: bytes):
data = b64.b64encode(boc).decode("utf-8")
r = self.execute_post("sendBoc", {"boc": data})
return r

def get_account(self, addr: str) -> Account:
result = self.execute_get("getAddressInformation", address=addr)
account = Account(addr=addr)
match result["state"], balance := int(result["balance"]):
case "active", _:
account.state = AccountState.ACTIVE
account.balance = balance
account.code = result["code"]
account.data = result["data"]
case "uninitialized", 0:
account.state = AccountState.EMPTY
account.balance = balance
case "uninitialized", _:
account.state = AccountState.UNINIT
account.balance = balance
return account
4 changes: 2 additions & 2 deletions rift/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@
from rift.types.model import Model
from rift.types.msg import (
CurrencyCollection,
ExternalMessage,
InboundExternalMsgInfo,
InboundExtMsgInfo,
InternalMessage,
InternalMsgInfo,
MessageFlag,
MessageMode,
SimpleLib,
StateInit,
ExternalMessage,
InboundExternalMsgInfo,
)
from rift.types.payload import Payload
from rift.types.ref import Ref
Expand Down
2 changes: 1 addition & 1 deletion rift/wallet/wallet_base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from rift.fift.types.cell import Cell
from rift.func.contract import Contract
from rift.network.network import Network
from rift.network.v2_network import Network
from rift.runtime.keystore import KeyStore
from rift.types.msg import ExternalMessage, MessageFlag, MessageMode

Expand Down
6 changes: 4 additions & 2 deletions rift/wallet/wallet_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from os import path

from rift.fift.types.cell import Cell
from rift.network.network import Network
from rift.network.v2_network import Network
from rift.runtime.config import Config
from rift.types.msg import MessageFlag, MessageMode
from rift.wallet.wallet_base import WalletBase
Expand Down Expand Up @@ -32,12 +32,14 @@ def send_message(
print(
"The wallet account is empty! Please send some TONs and proceed to deploying it.",
)
return
return -1
elif account.state == account.state.UNINIT:
print("Account is uninitialized, proceeding to deploy it ...")
r = wallet.deploy_wallet()
print(r)
print("Waiting 15 seconds to be sure wallet is deployed!")
# Reload the state and the data of the wallet
wallet.connect()
time.sleep(15)
return wallet.send_message(
message,
Expand Down
4 changes: 2 additions & 2 deletions rift/wallet/wallet_v3_r2.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from rift.fift.types.builder import Builder
from rift.fift.types.cell import Cell
from rift.network.network import Network
from rift.network.v2_network import Network
from rift.runtime.keystore import KeyStore
from rift.types.int_aliases import uint32, uint256
from rift.types.model import Model
Expand Down Expand Up @@ -49,7 +49,7 @@ def create_body(
b = b.uint(valid_until, 32)
seq = forced_seq_no if forced_seq_no is not None else self.seq_no()
b = b.uint(seq, 32)
b = b.uint(mode, 8)
if message:
b = b.uint(mode, 8)
b = b.ref(message)
return b.end()
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name="rift-framework",
version="0.9.14",
version="0.10.0",
description="A magical Python3 -> TON portal",
license="MIT",
packages=find_packages(exclude=["test"]),
Expand Down
2 changes: 1 addition & 1 deletion test/fift/test_tvm.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from pytest import fixture

from rift.fift.tvm import TVM, TVMResult
from rift.network.network import Network
from rift.network.v2_network import Network


@fixture
Expand Down
Loading