Substrate开发之三:开发ERC20合约并部署到substrate

配置Cargo.toml

我这里path直接配置了我拉下来的ink源代码

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
[package]
name = "erc20"
version = "3.0.0-rc8"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"

[dependencies]
ink_primitives = { version = "3.0.0-rc8", path = "../../ink/crates/primitives", default-features = false }
ink_metadata = { version = "3.0.0-rc8", path = "../../ink/crates/metadata", default-features = false, features = ["derive"], optional = true }
ink_env = { version = "3.0.0-rc8", path = "../../ink/crates/env", default-features = false }
ink_storage = { version = "3.0.0-rc8", path = "../../ink/crates/storage", default-features = false }
ink_lang = { version = "3.0.0-rc8", path = "../../ink/crates/lang", default-features = false }

scale = { package = "parity-scale-codec", version = "2", default-features = false, features = ["derive"] }
scale-info = { version = "1", default-features = false, features = ["derive"], optional = true }

[lib]
name = "erc20"
path = "lib.rs"
crate-type = ["cdylib"]

[features]
default = ["std"]
std = [
"ink_primitives/std",
"ink_metadata",
"ink_metadata/std",
"ink_env/std",
"ink_storage/std",
"ink_lang/std",
"scale/std",
"scale-info",
"scale-info/std",
]
ink-as-dependency = []
ink-experimental-engine = ["ink_env/ink-experimental-engine"]

合约代码

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#![cfg_attr(not(feature = "std"), no_std)]

use ink_lang as ink;

#[ink::contract]
mod erc20 {

use ink_lang::codegen::Env;
use ink_lang::codegen::EmitEvent;
use ink_storage::{
Mapping,
traits::SpreadAllocate,
};

#[ink(storage)]
#[derive(SpreadAllocate)]
pub struct Erc20 {
total_supply: Balance,
balances: Mapping<AccountId,Balance>,
allowances: Mapping<(AccountId,AccountId),Balance>,
owner: AccountId,
decimals: u8,
}

//--------------------------------定义事件--------------------------------
#[ink(event)]
pub struct Transfer {
#[ink(topic)]
from: Option<AccountId>,
#[ink(topic)]
to: Option<AccountId>,
value: Balance,
}

/// Event emitted when an approval occurs that `spender` is allowed to withdraw
/// up to the amount of `value` tokens from `owner`.
#[ink(event)]
pub struct Approval {
#[ink(topic)]
owner: AccountId,
#[ink(topic)]
spender: AccountId,
value: Balance,
}
//-----------------------------------------------------------------------
//-----------------------------定义Result类型-----------------------------
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Error {

InsufficientBalance,

InsufficientAllowance,

NotOwner,

OnlyOwner,
}
pub type Result<T> = core::result::Result<T, Error>;
//-----------------------------------------------------------------------


//-----------------------------定义trait特征------------------------------
// 声明方法参数及返回值类型
#[ink_lang::trait_definition]
pub trait BaseErc20 {
#[ink(message)]
fn total_supply(&self) -> Balance;

#[ink(message)]
fn balance_of(&self,owner:AccountId) -> Balance;

#[ink(message)]
fn mint(&mut self, owner: AccountId, value: Balance) -> Result<()> ;

#[ink(message)]
fn burn(&mut self, owner: AccountId, value: Balance) -> Result<()> ;

#[ink(message)]
fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> ;

#[ink(message)]
fn allowance(&self, owner: AccountId,spender: AccountId) -> Balance;

#[ink(message)]
fn owner(&self) -> AccountId;

#[ink(message)]
fn decimals(&self) -> u8;

#[ink(message)]
fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()>;

#[ink(message)]
fn transfer_from(&mut self, from: AccountId,to: AccountId, value: Balance) -> Result<()>;

}

impl Erc20 {
#[ink(constructor)]
pub fn new(initial_supply: Balance, decimals: u8) -> Self {
ink_lang::codegen::initialize_contract(|contract| {
Self::new_init(contract, initial_supply,decimals)
})
}

fn new_init(&mut self, initial_supply: Balance,decimals: u8) {
let caller = Self::env().caller();
self.balances.insert(&caller, &initial_supply);
self.owner = caller;
self.decimals = decimals;
self.total_supply = initial_supply;
}
}

//实现特征trait定义的方法
impl BaseErc20 for Erc20 {
#[ink(message)]
fn mint(&mut self, owner: AccountId, value: Balance) -> Result<()> {
if self.owner != self.env().caller(){
return Err(Error::OnlyOwner)
}
self.add_total_supply(value);
let owner_balance = self.balances.get(&owner).unwrap_or_default().clone();
self.balances.insert(&owner, &(owner_balance + value));
Ok(())
}

#[ink(message)]
fn burn(&mut self, owner: AccountId, value: Balance) -> Result<()>{
if owner != self.env().caller(){
return Err(Error::NotOwner)
}
let owner_balance = self.balances.get(&owner).unwrap_or_default().clone();
if owner_balance < value {
return Err(Error::InsufficientBalance)
}
self.sub_total_supply(value);
self.balances.insert(&owner,&(owner_balance - value));
Ok(())
}

#[ink(message)]
fn total_supply(&self) -> Balance{
self.total_supply
}

#[ink(message)]
fn balance_of(&self,owner:AccountId) -> Balance{
self.balances.get(owner).unwrap_or_default()
}

#[ink(message)]
fn approve(&mut self, spender: AccountId, value: Balance) -> Result<()> {
let owner = self.env().caller();
self.allowances.insert((&owner, &spender), &value);
self.env().emit_event(Approval {
owner,
spender,
value,
});
Ok(())
}

#[ink(message)]
fn allowance(&self,owner: AccountId,spender: AccountId) -> Balance{
self.allowance_impl(&owner, &spender)
}

#[ink(message)]
fn owner(&self) -> AccountId{
self.owner
}

#[ink(message)]
fn transfer(&mut self, to: AccountId, value: Balance) -> Result<()>{
let owner = self.env().caller();
self.transfer_from_to(&owner,&to,value)
}

#[ink(message)]
fn transfer_from(
&mut self,
from: AccountId,
to: AccountId,
value: Balance,
) -> Result<()> {
//caller = contractAddress
let caller = self.env().caller();
let allowance = self.allowance_impl(&from, &caller);
if allowance < value {
return Err(Error::InsufficientAllowance)
}
self.transfer_from_to(&from, &to, value)?;
self.allowances
.insert((&from, &caller), &(allowance - value));
Ok(())
}


#[ink(message)]
fn decimals(&self) -> u8{
self.decimals
}
}


impl Erc20 {
fn add_total_supply(&mut self, value: Balance) {
let total_supply = &mut self.total_supply;
let cur = total_supply;
self.total_supply = *cur + value;
}

fn sub_total_supply(&mut self, value: Balance){
let total_supply = &mut self.total_supply;
let cur = total_supply;
self.total_supply = *cur - value;
}

fn transfer_from_to(&mut self,from: &AccountId,to: &AccountId, value: Balance) -> Result<()>{
let from_balance = self.balances.get(from).unwrap_or_default().clone();
if from_balance < value{
return Err(Error::InsufficientBalance)
}
self.balances.insert(from, &(from_balance - value));
let to_balance = self.balances.get(to).unwrap_or_default().clone();
self.balances.insert(to, &(to_balance + value));
self.env().emit_event(Transfer {
from: Some(*from),
to: Some(*to),
value,
});
Ok(())
}

fn allowance_impl(&self, owner: &AccountId, spender: &AccountId) ->Balance{
self.allowances.get((owner, spender)).unwrap_or_default()
}
}
}

生成文件

1
cargo contract build

输入此命令后将生成三个文件,分别是:erc20.contract、erc20.wasm、metadata.json

部署合约

打开 https://polkadot.js.org/apps/ 并连接自己开启的substrate区块链,点击开发者->合约->upload & deploy code选择erc20.contract或erc20.wasm、metadata.json部署,输入构造参数即可部署合约到本地substrate区块链。