编写你的第一个链码

前面废话不多说了,链码是什么懂的都懂

资产转移链码
这个应用是一个基础的样例链码,这个链码可以产生一个账本(这个账本能创建资产,读,更新,删除资产,检查是否一个资产存在,转移资产)
为你的代码选个位置

就在home目录下面创建即可,并建立链码go文件(到时候把代码放进去)

// atcc is shorthand for asset transfer chaincode
   mkdir atcc && cd atcc
   go mod init atcc
   touch atcc.go

接下来是构建链码的几个模块函数
内务处理(housekeeping)
也就是给链码输入进一些必要的依赖
我们输入fabric合约api的包并且定义我们的samrtcontract
导入链码依赖包:

package main

import (
  "fmt"
  "log"
  "github.com/hyperledger/fabric-contract-api-go/contractapi"
)

// SmartContract provides functions for managing an Asset(智能合约提供的为了管理资产的函数)
   type SmartContract struct {
   
   contractapi.Contract
   }

接下来,添加一个结构Asset来表示在账本上的简单的资产

// Asset describes basic details of what makes up a simple asset
   type Asset struct {
   
    ID             string `json:"ID"`
    Color          string `json:"color"`
    Size           int    `json:"size"`
    Owner          string `json:"owner"`
    AppraisedValue int    `json:"appraisedValue"`
   }

建立链码
InitLedger函数来让账本有些基础数据

// InitLedger adds a base set of assets to the ledger(这个函数把一系列基础的资产加入到账本)
   func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
   
      assets := []Asset{
   
        {
   ID: "asset1", Color: "blue", Size: 5, Owner: "Tomoko", AppraisedValue: 300},
        {
   ID: "asset2", Color: "red", Size: 5, Owner: "Brad", AppraisedValue: 400},
        {
   ID: "asset3", Color: "green", Size: 10, Owner: "Jin Soo", AppraisedValue: 500},
        {
   ID: "asset4", Color: "yellow", Size: 10, Owner: "Max", AppraisedValue: 600},
        {
   ID: "asset5", Color: "black", Size: 15, Owner: "Adriana", AppraisedValue: 700},
        {
   ID: "asset6", Color: "white", Size: 15, Owner: "Michel", AppraisedValue: 800},
      }

   for _, asset := range assets {
   
      assetJSON, err := json.Marshal(asset)
      if err != nil {
   
        return err
      }

      err = ctx.GetStub().PutState(asset.ID, assetJSON)
      if err != nil {
   
        return fmt.Errorf("failed to put to world state. %v", err)
      }
    }

    return nil
  }

接下来写个函数来在账本上面创造一个还不存在的资产。写链码的时候,检查一下在账本上存在那些东西比直接操作要好。

// CreateAsset issues a new asset to the world state with given details.(函数发布一个新的资产到世界状态)
   func (s *SmartContract) CreateAsset(ctx contractapi.TransactionContextInterface, id string, color string, size int, owner string, appraisedValue int
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值