Quick Start
Install
go get github.com/yu-org/yu
Source code link: https://github.com/yu-org/yu/blob/main/apps/quickstart/chain.go
Develop an on-chain Writing
and Reading
package main
import (
"github.com/yu-org/yu/apps/poa"
"github.com/yu-org/yu/core/context"
"github.com/yu-org/yu/core/startup"
"github.com/yu-org/yu/core/tripod"
"net/http"
)
type QuickStart struct {
*tripod.Tripod
}
func NewQuickStart() *QuickStart {
tri := &QuickStart{
tripod.NewTripod(),
}
// 此处需要手动将自定义的 Writing 注册到 tripod 中,
tri.SetWritings(tri.WriteA)
// 此处需要手动将自定义的 Reading 注册到 tripod 中
tri.SetReadings(tri.ReadA)
return tri
}
type WriteRequest struct {
Key string `json:"key"`
Value string `json:"value"`
}
// Here is a custom development of a Writing.
// The Writing will be consensus and executed across the entire network.
func (q *QuickStart) WriteA(ctx *context.WriteContext) error {
// set this Writing lei cost (lei and gas are synonymous)
ctx.SetLei(100)
req := new(WriteRequest)
err := ctx.BindJson(req)
if err != nil {
return err
}
// Store data in on-chain state.
q.Set([]byte(req.Key), []byte(req.Value))
// Emit an event.
ctx.EmitStringEvent("execute success")
return nil
}
type ReadRequest struct {
Key string `json:"key"`
}
type ReadResponse struct {
Value string `json:"value"`
}
// Here is a custom development of a Reading
func (q *QuickStart) ReadA(ctx *context.ReadContext) {
req := new(ReadRequest)
err := ctx.BindJson(req)
if err != nil {
ctx.Err(http.StatusBadRequest, err)
return
}
value, err := q.Get([]byte(req.Key))
if err != nil {
ctx.ErrOk(err)
return
}
ctx.JsonOk(ReadResponse{Value: string(value)})
}
// Load tripods and start up the chain
func main() {
// default poa tripod config
poaCfg := poa.DefaultCfg(0)
// default yu config
yuCfg := startup.InitDefaultKernelConfig()
poaTri := poa.NewPoa(poaCfg)
qsTri := NewQuickStart()
startup.InitDefaultKernel(yuCfg).
WithTripods(poaTri, qsTri).
Startup()
}
Run
go build -o yu-example
./yu-example
At this point, a blockchain has been activated. In the future, more blockchain nodes can be added to build a blockchain network。