6

区块链多合约监听框架

 2 years ago
source link: https://studygolang.com/articles/35566
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

元宇宙的 “猴子.JPG”

最近什么都往元宇宙靠,什么“猴子.JPG”价值一套房,“虚拟土地.JPG”价值一套上海小别墅,大家还是要理性谨慎对待,最近很多交易所招人,面向监狱编程也是很火的一个概念,我们不推荐。

归根到底都是智能合约

智能合约我们可以从技术上先了解下,目前最六的是ETH,那么智能合约是如何运行的,我们该如何监听一些指定的智能合约,开源的方法有很多,但是都比较乱,一些开源的项目解构的也不太好,这边提供一个解构相对清晰的仓库供大家理解或使用https://github.com/Rennbon/ethmonitor ,觉得OK可要给star啊。

  1. 支持自定义业务handle
  2. 支持多合约监听
// 实现TxHandler
var _ ethmonitor.TxHandler = &Mock{}

type Mock struct {
}

type Mock struct {
}

// 持久化块高
func (m *Mock) SaveHeight(ctx context.Context, height *ethmonitor.BlockHeight) error {
    // 保存扫过的块高到自己喜欢的中间件
    return nil
}

// 启动monitor时加载初始化监听块高
func (m *Mock) LoadLastHeight(ctx context.Context) (*ethmonitor.BlockHeight, error) {
    // 从自己喜欢的中间件或许块高
    return big.NewInt(1), nil
}

// 具体业务处理
func (m *Mock) Do(ctx context.Context, info *ethmonitor.TxInfo) {

}

// 是否包含需要监控的合约地址
// NOTE: 如果是多智能合约监听,可以使用map维护多个
// 配套的,需要把这些合约的abi合并在初始化monitor时赋值给AbiStr,注意去重
func (m *Mock) ContainContact(ctx context.Context, address ethmonitor.ContractAddress) bool {
    return true
}

func main() {
    opt := &ethmonitor.Options{
        RpcUrl: "http://localhost:8545",
        AbiStr: `
[
    { "type" : "function", "name" : ""},
    {"internalType":"string","name":"symbol_","type":"string"}
    { "type" : "function", "name" : "overloadedNames", "stateMutability" : "view", "inputs": [ { "components": [ { "internalType": "uint256", "name": "_f",    "type": "uint256" }, { "internalType": "uint256", "name": "__f", "type": "uint256"}, { "internalType": "uint256", "name": "f", "type": "uint256"}],"internalType": "struct Overloader.F", "name": "f","type": "tuple"}]}
]`,
        Handler: &Mock{},
    }
    monitor, err := ethmonitor.New(opt)
    if err != nil {
        panic(err)
    }
    monitor.Run()
}

合约相关操作

// Action 智能合约的方法
type Action struct {
    Method string                 // 合约方法
    Inputs map[string]interface{} //合约入参及对应的value
}

// 如何解析智能合约对应的参数的value
// 对应abi方法为:     { "type" : "function", "name" : "send", "inputs" : [ { "name" : "amount", "type" : "uint256" } ] }
// 我们监控所得实体如下,可以通过反射获得
var act = &Action{
    Method : "send"
    Inputs : map[string]interface{}{"amount": big.NewInt(250)}
}

amount,ok := act.Inputs["amount"].(*big.Int)

if ok {
    fmt.Println(amount.String())
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK