ton 合约map批量同步和go调用

tact代码:

import "@stdlib/deploy";
import "@stdlib/ownable";
struct RoundInfo {
  orders: map<Int as uint32, BuyInfo>; 
  sum: Int as uint16;                
  arrLength: Int as uint16;           
}
struct BuyInfo {
  startLuckyNum: Int as uint16;    
  nifiNum: Int as uint16;            

message BatchSyncOrderMsg {
  round: Int as uint32;
  orders: map<Int as uint32, BuyInfo>;
}

contract Contract {
  rounds: map<Int as uint32, RoundInfo>;
  
  receive(msg: BatchSyncOrderMsg) {
    self.requireOwner();  
    let roundInfo: RoundInfo = self.rounds.get(msg.round)!!; 

    let totalNifiNum: Int = 0;
    foreach (orderNumber, buyInfo in msg.orders) {
      roundInfo.orders.set(orderNumber, buyInfo);
      totalNifiNum += buyInfo.nifiNum;
      roundInfo.sequence += 1;
    }
  }

go调用代码:

type BatchSyncOrderMsg struct {
	RoundId uint32
	Orders  tlb.HashmapE[tlb.Uint32, tlb.Ref[chainservice.BuyInfo]] 
}
func (t TonApiServiceImpl) BatchSyncOrder(ctx context.Context, roundId uint32, orders map[uint32]chainservice.BuyInfo) (string, error) {
	msg := BatchSyncOrderMsg3{
		RoundId: roundId,
	}

	var keys []tlb.Uint32
	var values []tlb.Ref[chainservice.BuyInfo]
	for key, value := range orders {
		keys = append(keys, tlb.Uint32(key))
		values = append(values, tlb.Ref[chainservice.BuyInfo]{Value: value})
	}
	msg.Orders = tlb.NewHashmapE(keys, values)
	return t.InvokeContract(ctx, roundContractConfig.ContractAddress, BatchSyncOrderMethodId, msg, 51_000_000)
}

func TestTonApiServiceImpl_BatchSyncOrder(t *testing.T) {
	var boughtRoundNum uint16 = 0
	var startLuckNum uint16 = 1
	orders := make(map[uint32]chainservice.BuyInfo)
	for i := 1; i <= int(ordersMax); i++ {
		buyNum := maxRoundNum / uint16(ordersMax)
		if boughtRoundNum+buyNum > maxRoundNum {
			buyNum = maxRoundNum - boughtRoundNum
		}
		if buyNum == 0 {
			break
		}
		orderID := StartOrderID + uint32(i)

		orders[orderID] = chainservice.BuyInfo{
			StartLuckNum: startLuckNum,
			Amount:       buyNum,
		}
		startLuckNum += buyNum
		boughtRoundNum += buyNum
	}

	txHash, err := tonService.BatchSyncOrder(context.Background(), RoundId, orders, nil)
	if err != nil {
		t.Error(err)
	}

	fmt.Println("txHash:", txHash)

}

这边截取部分代码,

posted @ 2024-10-19 17:20  若-飞  阅读(6)  评论(0编辑  收藏  举报