0%

solidity | remix 部署到 Ropsten

这里简单的讲一下 remix 部署到 Ropsten,以及用 python 如何与其交互。

编译

首先,我们编辑好我们的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pragma solidity >=0.4.22 <0.9.0;
contract SimpleContract{
uint storeData;

modifier mustOver10 (uint value){
require(value >= 10);
_;
}

function set(uint x) public mustOver10(x){
storeData = x;
}

function get() public constant returns(uint) {
return storeData;
}
}

然后使用编译器,进行预编译,看看是否有语法上的错误。

这里要注意的点是,不同编译器,语法不一定相同,如上面的代码在 0.8 中编译不通过。

我们在这个页面的下面复制一下 ABI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[
{
"constant": false,
"inputs": [
{
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "get",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]

ps: 你也可以开源你的合约。

部署

之所以,想要部署到 ropsten 中,主要是用 python 与其交互。

图中的 1 是选择部署环境

  • JavaScript VM
    • 本地虚拟环境进行调试测试
  • Injected Web3
    • 线上环境,具体哪个,取决于你的 metamask 的选择网络
  • Web3 Provider
    • 这个可以是你自己搭建的网络

这里,我们选择 Injected Web3 ,部署完之后,会在图中 2 的位置出现合约地址,这里是

交互

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from web3 import Web3

abi = """
[{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]
"""

w3 = Web3(Web3.HTTPProvider("https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"))
contractObj = w3.eth.contract(
address=Web3.toChecksumAddress("0xB5B990E8B01f00d2C319D427b395d00435d910d5"), abi=abi)

print(contractObj.functions.get().call())

dex_address = ""
dex_private = ""


def set_number_5():
tx_dic = contractObj.functions.set(
5
). \
buildTransaction(
{
'gas': 500000,
}
)

nonce = w3.eth.getTransactionCount(dex_address)
tx_dic["nonce"] = nonce
tx_dic['gasPrice'] = w3.eth.gasPrice
sign_tx = w3.eth.account.signTransaction(tx_dic, private_key=dex_private)
txn_hash = w3.eth.sendRawTransaction(sign_tx.rawTransaction)
print(Web3.toHex(txn_hash))


def set_number_10():
tx_dic = contractObj.functions.set(
10
). \
buildTransaction(
{
'gas': 500000,
}
)

nonce = w3.eth.getTransactionCount(dex_address)
tx_dic["nonce"] = nonce
tx_dic['gasPrice'] = w3.eth.gasPrice
sign_tx = w3.eth.account.signTransaction(tx_dic, private_key=dex_private)
txn_hash = w3.eth.sendRawTransaction(sign_tx.rawTransaction)
print(Web3.toHex(txn_hash))

if __name__ == '__main__':
set_number_10()
请我喝杯咖啡吧~