/
ibc.go
424 lines (373 loc) · 13.6 KB
/
ibc.go
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package keeper
import (
"errors"
"fmt"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/common"
ethermint "github.com/FiboChain/fbc/app/types"
sdk "github.com/FiboChain/fbc/libs/cosmos-sdk/types"
ibctransfertypes "github.com/FiboChain/fbc/libs/ibc-go/modules/apps/transfer/types"
ibcclienttypes "github.com/FiboChain/fbc/libs/ibc-go/modules/core/02-client/types"
tmtypes "github.com/FiboChain/fbc/libs/tendermint/types"
"github.com/FiboChain/fbc/x/erc20/types"
evmtypes "github.com/FiboChain/fbc/x/evm/types"
)
// OnMintVouchers after minting vouchers on this chain
func (k Keeper) OnMintVouchers(ctx sdk.Context, vouchers sdk.SysCoins, receiver string) error {
if err := k.ConvertVouchers(ctx, receiver, vouchers); err != nil {
k.Logger(ctx).Error(
fmt.Sprintf("Failed to convert vouchers to evm tokens for receiver %s, coins %s. Receive error %s",
receiver, vouchers.String(), err))
return err
}
return nil
}
// OnUnescrowNatives after unescrow natives on this chain
func (k Keeper) OnUnescrowNatives(ctx sdk.Context, natives sdk.SysCoins, receiver string) error {
if err := k.ConvertNatives(ctx, receiver, natives); err != nil {
k.Logger(ctx).Error(
fmt.Sprintf("Failed to convert natives to evm tokens for receiver %s, coins %s. Receive error %s",
receiver, natives.String(), err))
return err
}
return nil
}
// ConvertVouchers convert vouchers into evm tokens.
func (k Keeper) ConvertVouchers(ctx sdk.Context, from string, vouchers sdk.SysCoins) error {
if len(strings.TrimSpace(from)) == 0 {
return errors.New("empty from address string is not allowed")
}
fromAddr, err := sdk.AccAddressFromBech32(from)
if err != nil {
return err
}
params := k.GetParams(ctx)
for _, c := range vouchers {
// okc1:xxb----->okc2:ibc/xxb---->okc2:erc20/xxb
if err := k.ConvertVoucherToERC20(ctx, fromAddr, c, params.EnableAutoDeployment); err != nil {
return err
}
}
return nil
}
// ConvertNatives convert natives into evm tokens.
func (k Keeper) ConvertNatives(ctx sdk.Context, from string, vouchers sdk.SysCoins) error {
if len(strings.TrimSpace(from)) == 0 {
return errors.New("empty from address string is not allowed")
}
fromAddr, err := sdk.AccAddressFromBech32(from)
if err != nil {
return err
}
for _, c := range vouchers {
// if there is a contract associated with this native coin,
// the native coin come from native erc20
// okc1:erc20/xxb----->okc2:ibc/xxb---->okc1:ibc/yyb---->okc2:erc20/xxb
if contract, found := k.GetContractByDenom(ctx, c.Denom); found {
if err := k.ConvertNativeToERC20(ctx, fromAddr, c, contract); err != nil {
return err
}
}
}
return nil
}
// ConvertVoucherToERC20 convert voucher into evm token.
func (k Keeper) ConvertVoucherToERC20(ctx sdk.Context, from sdk.AccAddress, voucher sdk.SysCoin, autoDeploy bool) error {
k.Logger(ctx).Info("convert vouchers into evm tokens",
"fromBech32", from.String(),
"fromEth", common.BytesToAddress(from.Bytes()).String(),
"voucher", voucher.String())
if !types.IsValidIBCDenom(voucher.Denom) {
return fmt.Errorf("coin %s is not supported for wrapping", voucher.Denom)
}
var err error
contract, found := k.GetContractByDenom(ctx, voucher.Denom)
if !found {
// automated deployment contracts
if !autoDeploy {
k.Logger(ctx).Error("no contract found and not auto deploy for the denom", "denom", voucher.Denom)
return types.ErrNoContractNotAuto
}
contract, err = k.DeployModuleERC20(ctx, voucher.Denom)
if err != nil {
return err
}
k.SetContractForDenom(ctx, voucher.Denom, contract)
k.Logger(ctx).Info("contract created for coin", "contract", contract.String(), "denom", voucher.Denom)
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypDeployModuleERC20,
sdk.NewAttribute(types.AttributeKeyContractAddr, contract.String()),
sdk.NewAttribute(ibctransfertypes.AttributeKeyDenom, voucher.Denom),
),
})
}
// 1. transfer voucher from user address to contact address in bank
if err := k.bankKeeper.SendCoins(ctx, from, sdk.AccAddress(contract.Bytes()), sdk.NewCoins(voucher)); err != nil {
return err
}
// 2. call contract, mint token to user address in contract
if _, err := k.CallModuleERC20(
ctx,
contract,
types.ContractMintMethod,
common.BytesToAddress(from.Bytes()),
voucher.Amount.BigInt()); err != nil {
return err
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypLock,
sdk.NewAttribute(types.AttributeKeyFrom, from.String()),
sdk.NewAttribute(types.AttributeKeyTo, contract.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, voucher.String()),
),
sdk.NewEvent(
types.EventTypCallModuleERC20,
sdk.NewAttribute(types.AttributeKeyContractAddr, contract.String()),
sdk.NewAttribute(types.AttributeKeyContractMethod, types.ContractMintMethod),
sdk.NewAttribute(ibctransfertypes.AttributeKeyReceiver, from.String()),
sdk.NewAttribute(ibctransfertypes.AttributeKeyAmount, voucher.Amount.BigInt().String()),
),
})
return nil
}
// ConvertNativeToERC20 convert native into evm token.
func (k Keeper) ConvertNativeToERC20(ctx sdk.Context, from sdk.AccAddress, native sdk.SysCoin, contract common.Address) error {
k.Logger(ctx).Info("convert native into evm tokens",
"fromBech32", from.String(),
"fromEth", common.BytesToAddress(from.Bytes()).String(),
"native", native.String(),
"contract", contract.String())
// 1. transfer native from user address to module address and burn them
if err := k.supplyKeeper.SendCoinsFromAccountToModule(ctx, from, types.ModuleName, sdk.NewCoins(native)); err != nil {
return err
}
if err := k.supplyKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(native)); err != nil {
return err
}
// 2. call contract, mint token to user address in contract
if _, err := k.CallModuleERC20(
ctx,
contract,
types.ContractMintMethod,
common.BytesToAddress(from.Bytes()),
native.Amount.BigInt()); err != nil {
return err
}
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypBurn,
sdk.NewAttribute(types.AttributeKeyFrom, from.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, native.String()),
),
sdk.NewEvent(
types.EventTypCallModuleERC20,
sdk.NewAttribute(types.AttributeKeyContractAddr, contract.String()),
sdk.NewAttribute(types.AttributeKeyContractMethod, types.ContractMintMethod),
sdk.NewAttribute(ibctransfertypes.AttributeKeyReceiver, from.String()),
sdk.NewAttribute(ibctransfertypes.AttributeKeyAmount, native.Amount.BigInt().String()),
),
})
return nil
}
// DeployModuleERC20 deploy an embed erc20 contract
func (k Keeper) DeployModuleERC20(ctx sdk.Context, denom string) (common.Address, error) {
implContract, found := k.GetImplementTemplateContract(ctx)
if !found {
return common.Address{}, errors.New("not found implement contract")
}
proxyContract, found := k.GetProxyTemplateContract(ctx)
if !found {
return common.Address{}, errors.New("not found proxy contract")
}
// 1. deploy implement contract
byteCode := common.Hex2Bytes(implContract.Bin)
_, implRes, err := k.callEvmByModule(ctx, nil, big.NewInt(0), byteCode)
if err != nil {
return common.Address{}, err
}
// 2. deploy proxy contract
byteCode = common.Hex2Bytes(proxyContract.Bin)
implInput, err := implContract.ABI.Pack("initialize", denom, uint8(0))
if err != nil {
return common.Address{}, err
}
input, err := proxyContract.ABI.Pack("", implRes.ContractAddress, implInput)
if err != nil {
return common.Address{}, err
}
data := append(byteCode, input...)
_, res, err := k.callEvmByModule(ctx, nil, big.NewInt(0), data)
if err != nil {
return common.Address{}, err
}
return res.ContractAddress, nil
}
// CallModuleERC20 call a method of ModuleERC20 contract
func (k Keeper) CallModuleERC20(ctx sdk.Context, contract common.Address, method string, args ...interface{}) ([]byte, error) {
k.Logger(ctx).Info("call erc20 module contract", "contract", contract.String(), "method", method, "args", args)
implContract, found := k.GetImplementTemplateContract(ctx)
if !found {
return nil, errors.New("not found implement contract")
}
data, err := implContract.ABI.Pack(method, args...)
if err != nil {
return nil, err
}
_, res, err := k.callEvmByModule(ctx, &contract, big.NewInt(0), data)
if err != nil {
return nil, fmt.Errorf("call contract failed: %s, %s, %s", contract.Hex(), method, err)
}
return res.Ret, nil
}
func (k Keeper) CallModuleERC20Proxy(ctx sdk.Context, contract common.Address, method string, args ...interface{}) ([]byte, error) {
k.Logger(ctx).Info("call proxy erc20 module contract", "contract", contract.String(), "method", method, "args", args)
proxyContract, found := k.GetProxyTemplateContract(ctx)
if !found {
return nil, errors.New("not found proxy contract")
}
data, err := proxyContract.ABI.Pack(method, args...)
if err != nil {
return nil, err
}
_, res, err := k.callEvmByModule(ctx, &contract, big.NewInt(0), data)
if err != nil {
return nil, fmt.Errorf("call contract failed: %s, %s, %s", contract.Hex(), method, err)
}
return res.Ret, nil
}
// callEvmByModule execute an evm message from native module
func (k Keeper) callEvmByModule(ctx sdk.Context, to *common.Address, value *big.Int, data []byte) (*evmtypes.ExecutionResult, *evmtypes.ResultData, error) {
config, found := k.evmKeeper.GetChainConfig(ctx)
if !found {
return nil, nil, types.ErrChainConfigNotFound
}
chainIDEpoch, err := ethermint.ParseChainID(ctx.ChainID())
if err != nil {
return nil, nil, err
}
acc := k.accountKeeper.GetAccount(ctx, types.IbcEvmModuleBechAddr)
if acc == nil {
acc = k.accountKeeper.NewAccountWithAddress(ctx, types.IbcEvmModuleBechAddr)
}
nonce := acc.GetSequence()
txHash := tmtypes.Tx(ctx.TxBytes()).Hash(ctx.BlockHeight())
ethTxHash := common.BytesToHash(txHash)
gasLimit := ctx.GasMeter().Limit()
if gasLimit == sdk.NewInfiniteGasMeter().Limit() {
gasLimit = k.evmKeeper.GetParams(ctx).MaxGasLimitPerTx
}
st := evmtypes.StateTransition{
AccountNonce: nonce,
Price: big.NewInt(0),
GasLimit: gasLimit,
Recipient: to,
Amount: value,
Payload: data,
Csdb: evmtypes.CreateEmptyCommitStateDB(k.evmKeeper.GenerateCSDBParams(), ctx),
ChainID: chainIDEpoch,
TxHash: ðTxHash,
Sender: types.IbcEvmModuleETHAddr,
Simulate: ctx.IsCheckTx(),
TraceTx: false,
TraceTxLog: false,
}
executionResult, resultData, err, innertxs, contracts := st.TransitionDb(ctx, config)
if !ctx.IsCheckTx() && !ctx.IsTraceTx() {
k.addEVMInnerTx(ethTxHash.Hex(), innertxs, contracts)
}
if err != nil {
return nil, nil, err
}
st.Csdb.Commit(false) // write code to db
acc.SetSequence(nonce + 1)
k.accountKeeper.SetAccount(ctx, acc)
return executionResult, resultData, err
}
// IbcTransferVouchers transfer vouchers to other chain by ibc
func (k Keeper) IbcTransferVouchers(ctx sdk.Context, from, to string, vouchers sdk.SysCoins) error {
if len(strings.TrimSpace(from)) == 0 {
return errors.New("empty from address string is not allowed")
}
fromAddr, err := sdk.AccAddressFromBech32(from)
if err != nil {
return err
}
if len(strings.TrimSpace(to)) == 0 {
return errors.New("to address cannot be empty")
}
k.Logger(ctx).Info("transfer vouchers to other chain by ibc", "from", from, "to", to, "vouchers", vouchers)
for _, c := range vouchers {
if _, found := k.GetContractByDenom(ctx, c.Denom); !found {
return fmt.Errorf("coin %s is not supported", c.Denom)
}
// okc2:erc20/xxb----->okc2:ibc/xxb---ibc--->okc1:xxb
if err := k.ibcSendTransfer(ctx, fromAddr, to, c); err != nil {
return err
}
}
return nil
}
// IbcTransferNative20 transfer native20 to other chain by ibc
func (k Keeper) IbcTransferNative20(ctx sdk.Context, from, to string, native20s sdk.SysCoins, portID, channelID string) error {
if len(strings.TrimSpace(from)) == 0 {
return errors.New("empty from address string is not allowed")
}
fromAddr, err := sdk.AccAddressFromBech32(from)
if err != nil {
return err
}
if len(strings.TrimSpace(to)) == 0 {
return errors.New("to address cannot be empty")
}
k.Logger(ctx).Info("transfer native20 to other chain by ibc", "from", from, "to", to, "vouchers", native20s)
for _, c := range native20s {
if _, found := k.GetContractByDenom(ctx, c.Denom); !found {
return fmt.Errorf("coin %s is not supported", c.Denom)
}
// okc2:erc20/xxb----->okc2:ibc/xxb---ibc--->okc1:xxb
if err := k.ibcSendTransferWithChannel(ctx, fromAddr, to, c, portID, channelID); err != nil {
return err
}
}
return nil
}
func (k Keeper) ibcSendTransfer(ctx sdk.Context, sender sdk.AccAddress, to string, coin sdk.Coin) error {
// Coin needs to be a voucher so that we can extract the channel id from the denom
channelID, err := k.GetSourceChannelID(ctx, coin.Denom)
if err != nil {
return err
}
// Transfer coins to receiver through IBC
params := k.GetParams(ctx)
timeoutTimestamp := uint64(ctx.BlockTime().UnixNano()) + params.IbcTimeout
timeoutHeight := ibcclienttypes.ZeroHeight()
return k.transferKeeper.SendTransfer(
ctx,
ibctransfertypes.PortID,
channelID,
sdk.NewCoinAdapter(coin.Denom, sdk.NewIntFromBigInt(coin.Amount.BigInt())),
sender,
to,
timeoutHeight,
timeoutTimestamp,
)
}
func (k Keeper) ibcSendTransferWithChannel(ctx sdk.Context, sender sdk.AccAddress, to string, coin sdk.Coin, portID, channelID string) error {
// Transfer coins to receiver through IBC
params := k.GetParams(ctx)
timeoutTimestamp := uint64(ctx.BlockTime().UnixNano()) + params.IbcTimeout
timeoutHeight := ibcclienttypes.ZeroHeight()
return k.transferKeeper.SendTransfer(
ctx,
portID,
channelID,
sdk.NewCoinAdapter(coin.Denom, sdk.NewIntFromBigInt(coin.Amount.BigInt())),
sender,
to,
timeoutHeight,
timeoutTimestamp,
)
}