// 修改飞机所属者 // 可用于购买飞机 // Failure 0x11 / 0x12 / 0x16 // Success 0x01 public static byte[] ChangeOwner(BigInteger tokenId, byte[] fromOwner, byte[] toOwner) { byte[] aircraftInfo = Storage.Get(Storage.CurrentContext, tokenId.AsByteArray()); if (aircraftInfo.Length == 0) { ChangeOwnerLog(tokenId, fromOwner, toOwner); return(new byte[] { 0x11 }); } Aircraft aircraft = (Aircraft)Helper.Deserialize(aircraftInfo); if (aircraft.owner != fromOwner) { ChangeOwnerLog(tokenId, fromOwner, toOwner); return(new byte[] { 0x12 }); } BigInteger currentTimestamp = Blockchain.GetHeader(Blockchain.GetHeight()).Timestamp; if (aircraft.auctionTime < currentTimestamp) { ChangeOwnerLog(tokenId, fromOwner, toOwner); return(new byte[] { 0x16 }); } // 执行所属转移 aircraft.owner = toOwner; aircraft.auctionTime = 1525104000; // 较早的时间戳,清除售卖中状态 byte[] aircraftData = Helper.Serialize(aircraft); Storage.Put(Storage.CurrentContext, tokenId.AsByteArray(), aircraftData); ChangeOwnerLog(tokenId, fromOwner, toOwner); return(new byte[] { 0x01 }); }
public static bool destoryByBu(string name, byte[] from, BigInteger value) { if (from.Length != 20) { return(false); } if (value <= 0) { return(false); } var key = getNameKey(name.AsByteArray()); byte[] token = Storage.Get(Storage.CurrentContext, key); if (token.Length == 0) { return(false); } if (!transfer(name, from, null, value)) { throw new InvalidOperationException("Operation is error."); } Tokenized t = Helper.Deserialize(token) as Tokenized; t.totalSupply = t.totalSupply - value; Storage.Put(Storage.CurrentContext, key, Helper.Serialize(t)); return(true); }
public static byte[] InAuction(BigInteger tokenId, byte[] owner, int price) { byte[] aircraftInfo = Storage.Get(Storage.CurrentContext, tokenId.AsByteArray()); if (aircraftInfo.Length == 0) { InAuctionLog(tokenId, owner, price, -1); return(new byte[] { 0x11 }); } Aircraft aircraft = (Aircraft)Helper.Deserialize(aircraftInfo); if (aircraft.owner != owner) { InAuctionLog(tokenId, owner, price, -1); return(new byte[] { 0x12 }); } aircraft.price = price; // 当前时间增加三天,单位为秒 aircraft.auctionTime = Blockchain.GetHeader(Blockchain.GetHeight()).Timestamp + 3 * 24 * 60 * 60; byte[] aircraftData = Helper.Serialize(aircraft); Storage.Put(Storage.CurrentContext, tokenId.AsByteArray(), aircraftData); InAuctionLog(tokenId, owner, price, aircraft.auctionTime); return(new byte[] { 0x01 }); }
public static BigInteger[] getPayAmounts(byte[][] payIds, BigInteger lastPayResolveDeadline) { BasicMethods.assert(BasicMethods._isByte32s(payIds), "payIds invalid"); BasicMethods.assert(lastPayResolveDeadline >= 0, "lastPayResolveDeadline less than zero"); BigInteger[] amounts = new BigInteger[payIds.Length]; BigInteger now = Blockchain.GetHeight(); for (var i = 0; i < payIds.Length; i++) { byte[] payInfoBs = Storage.Get(Storage.CurrentContext, PayInfoPrefix.Concat(payIds[i])); PayInfo payInfo = new PayInfo(); if (payInfoBs.Length > 0) { payInfo = Helper.Deserialize(payInfoBs) as PayInfo; } if (payInfo.resolveDeadline == 0) { BasicMethods.assert(now > lastPayResolveDeadline, "payment is not finalized"); } else { BasicMethods.assert(now > payInfo.resolveDeadline, "payment is not finalized"); } amounts[i] = payInfo.amount; } return(amounts); }
public static bool transferFrom(byte[] addrTo, BigInteger tokenID) { if (addrTo.Length != 20) { return(false); } StorageMap tokenMap = Storage.CurrentContext.CreateMap("token"); var data = tokenMap.Get(tokenID.AsByteArray()); if (data.Length > 0) { Token token = Helper.Deserialize(data) as Token; if (!Runtime.CheckWitness(token.approved) && !Runtime.CheckWitness(superAdmin)) { return(false); } var addrFrom = token.owner; token.owner = addrTo; tokenMap.Put(tokenID.AsByteArray(), Helper.Serialize(token)); addrNFTlistRemove(addrFrom, tokenID); addrNFTlistAdd(addrTo, tokenID); onTransfer(addrFrom, addrTo, 1); onNFTTransfer(addrFrom, addrTo, tokenID); return(true); } return(false); }
public static void Main() { // create struct instance Person p = new Person(); p.Name = "bob"; p.Age = 20; Runtime.Notify(p.Name); Runtime.Notify(p.Age); // serialize struct instance to byte[] byte[] b = Helper.Serialize(p); // deserialize byte[] to struct Person p2 = (Person)Helper.Deserialize(b); Runtime.Notify(p2.Name); Runtime.Notify(p2.Age); // create struct array Person[] array = new Person[] { new Person { Name = "tom", Age = 18 }, new Person { Name = "jack", Age = 20 } }; }
/** * @dev Computes the next gen0 auction starting price, given * the average of the past 5 prices + 50%. */ private static BigInteger _computeNextGen0Price() { BigInteger nextPrice = GEN0_MAX_PRICE; byte[] v = (byte[])Storage.Get(Storage.CurrentContext, "gene0Record"); if (v.Length == 0) { nextPrice = GEN0_MAX_PRICE; } else { Gene0Record gene0Record; object[] infoRec = (object[])Helper.Deserialize(v); gene0Record = (Gene0Record)(object)infoRec; BigInteger sum = gene0Record.lastPrice0 + gene0Record.lastPrice1 + gene0Record.lastPrice2 + gene0Record.lastPrice3 + gene0Record.lastPrice4; if (gene0Record.totalSellCount < 5) { nextPrice = GEN0_MAX_PRICE; } else { nextPrice = (sum / 5) * 3 / 2; if (nextPrice < GEN0_MIN_PRICE) { nextPrice = GEN0_MIN_PRICE; } } } return(nextPrice); }
//函数进栈损耗太大,不要这么实现了 //private static byte[] byteLen(BigInteger n) //{ // byte[] v = n.AsByteArray(); // if (v.Length > 2) // throw new Exception("not support"); // if (v.Length < 2) // v = v.Concat(new byte[1] { 0x00 }); // if (v.Length < 2) // v = v.Concat(new byte[1] { 0x00 }); // return v; //} public static TransferInfo getTXInfo(byte[] txid) { byte[] keytxid = new byte[] { 0x12 }.Concat(txid); byte[] v = Storage.Get(Storage.CurrentContext, keytxid); if (v.Length == 0) { return(null); } //老式实现方法 //TransferInfo info = new TransferInfo(); //int seek = 0; //var fromlen = (int)v.Range(seek, 2).AsBigInteger(); //seek += 2; //info.from = v.Range(seek, fromlen); //seek += fromlen; //var tolen = (int)v.Range(seek, 2).AsBigInteger(); //seek += 2; //info.to = v.Range(seek, tolen); //seek += tolen; //var valuelen = (int)v.Range(seek, 2).AsBigInteger(); //seek += 2; //info.value = v.Range(seek, valuelen).AsBigInteger(); //return info; //新式实现方法只要一行 return(Helper.Deserialize(v) as TransferInfo); }
private static bool _updateBalance(byte[] _walletId, byte[] _tokenAddress, BigInteger _amount, byte _mathOperation) { BasicMethods.assert(_amount >= 0, "amount is less than zero"); Wallet w = getWallet(_walletId); BasicMethods.assert(BasicMethods._isLegalAddress(w.theOperator), "wallet Object does not exist"); byte[] wBalanceBs = Storage.Get(Storage.CurrentContext, WalletsBalancesPrefix.Concat(_walletId)); Map <byte[], BigInteger> wBalanceMap = new Map <byte[], BigInteger>(); if (wBalanceBs.Length > 0) { wBalanceMap = Helper.Deserialize(wBalanceBs) as Map <byte[], BigInteger>; } if (!wBalanceMap.HasKey(_tokenAddress)) { wBalanceMap[_tokenAddress] = 0; } if (_mathOperation == getStandardMathOperation().add) { wBalanceMap[_tokenAddress] += _amount; } else if (_mathOperation == getStandardMathOperation().sub) { wBalanceMap[_tokenAddress] -= _amount; BasicMethods.assert(wBalanceMap[_tokenAddress] >= 0, "balance is less than zero"); } else { BasicMethods.assert(false, "math operation illegal"); } Storage.Put(Storage.CurrentContext, WalletsBalancesPrefix.Concat(_walletId), Helper.Serialize(wBalanceMap)); return(true); }
public static object addPauser(byte[] invoker, byte[] account) { BasicMethods.assert(Runtime.CheckWitness(invoker), "Checkwitness failed"); // make sure the invoker is one effective pauser Map <byte[], bool> pausers = new Map <byte[], bool>(); byte[] pauserBs = Storage.Get(Storage.CurrentContext, PauserKey); if (pauserBs.Length > 0) { pausers = Helper.Deserialize(pauserBs) as Map <byte[], bool>; } byte[] admin = BasicMethods.getAdmin(); if (!invoker.Equals(admin)) { BasicMethods.assert(pausers.HasKey(invoker), "invoker is not one pauser"); BasicMethods.assert(pausers[invoker], "invoker is an effective pauser"); } // update the pausers map pausers[account] = true; Storage.Put(Storage.CurrentContext, PauserKey, Helper.Serialize(pausers)); PauserAdded(account); return(true); }
public static Record getOwner(string node) { var data = Storage.Get(Storage.CurrentContext, node); var record = Helper.Deserialize(data) as Record; return(record); }
public static object TestMap() { StorageContext context = Storage.CurrentContext; Map <string, int> m = new Map <string, int>(); int value = 100; //m["hello"] = "world"; m["key"] = value; byte[] b = Helper.Serialize(m); Storage.Put(context, "tx", b); byte[] v = Storage.Get(context, "tx"); Map <string, int> b2 = (Map <string, int>)Helper.Deserialize(v); //&& b2["hello"] == "world" if (b2 != null && (int)b2["key"] == value) { Storage.Put(context, "result", "true"); return(b); } Storage.Put(context, "result", "false"); return(false); }
public static object resolvePaymentByConditions(byte[] resolvePayRequestBs) { PbChain.ResolvePayByConditionsRequest resolvePayRequest = new PbChain.ResolvePayByConditionsRequest(); resolvePayRequest = (PbChain.ResolvePayByConditionsRequest)Helper.Deserialize(resolvePayRequestBs); PbEntity.ConditionalPay pay = Helper.Deserialize(resolvePayRequest.condPay) as PbEntity.ConditionalPay; PbEntity.TransferFunction function = pay.transferFunc; byte funcType = function.logicType; BigInteger amount = 0; PbEntity.TransferFunctionType TransferFunctionType = PbEntity.getTransferFunctionType(); if (funcType == TransferFunctionType.BOOLEAN_AND) { amount = _calculateBooleanAndPayment(pay, resolvePayRequest.hashPreimages); } else if (funcType == TransferFunctionType.BOOLEAN_OR) { amount = _calculateBooleanOrPayment(pay, resolvePayRequest.hashPreimages); } else if (_isNumericLogic(funcType)) { amount = _calculateNumericLogicPayment(pay, resolvePayRequest.hashPreimages, funcType); } else { BasicMethods.assert(false, "error"); } byte[] payHash = SmartContract.Sha256(resolvePayRequest.condPay); _resolvePayment(pay, payHash, amount); return(true); }
public static bool setRWProperties(BigInteger tokenID, string rwProperties) { if (!isOpen() && !Runtime.CheckWitness(superAdmin)) { return(false); } StorageMap tokenMap = Storage.CurrentContext.CreateMap("token"); var data = tokenMap.Get(tokenID.AsByteArray()); if (data.Length > 0) { Token token = Helper.Deserialize(data) as Token; if (!Runtime.CheckWitness(token.owner) && !Runtime.CheckWitness(superAdmin)) { return(false); } token.rwProperties = rwProperties; tokenMap.Put(token.token_id.AsByteArray(), Helper.Serialize(token)); onNFTModify(tokenID, "rwProperties", rwProperties); return(true); } return(false); }
//增发货币 public static bool increaseByBu(string name, byte[] to, BigInteger value) { if (to.Length != 20) { return(false); } if (value <= 0) { return(false); } var key = getNameKey(name.AsByteArray()); byte[] token = Storage.Get(Storage.CurrentContext, key); if (token.Length == 0) { return(false); } transfer(name, null, to, value); Tokenized t = Helper.Deserialize(token) as Tokenized; t.totalSupply = t.totalSupply + value; Storage.Put(Storage.CurrentContext, key, Helper.Serialize(t)); return(true); }
//销毁货币 public static bool destoryByBu(string name, byte[] from, BigInteger value) { if (from.Length != 20) { return(false); } if (value <= 0) { return(false); } var key = new byte[] { 0x12 }.Concat(name.AsByteArray()); byte[] token = Storage.Get(Storage.CurrentContext, key); if (token.Length == 0) { return(false); } transfer(name, from, null, value); Tokenized t = Helper.Deserialize(token) as Tokenized; t.totalSupply = t.totalSupply - value; Storage.Put(Storage.CurrentContext, key, Helper.Serialize(t)); return(true); }
private static bool Announce(byte[] address) { if (Runtime.CheckWitness(Owner)) { return(false); } Runtime.Notify("0"); //Auction auction = (Auction)Storage.Get(Storage.CurrentContext, "auction").Deserialize(); Auction auction = (Auction)Helper.Deserialize(Storage.Get("auction")); Runtime.Notify("1"); uint now = Runtime.Time; Runtime.Notify("11"); uint test = auction.endOfBidding; Runtime.Notify("12"); if (now >= test) { return(false); } Runtime.Notify("2"); if (!auction.AnnounceBidder(address)) { return(false); } Runtime.Notify("3"); Transferred(null, address, 1000); Runtime.Notify("4"); //Storage.Put(Storage.CurrentContext, "auction", auction.Serialize()); Storage.Put("auction", Helper.Serialize(auction)); Runtime.Notify("5"); Storage.Put("totalSupply", BytesToBigInteger(Storage.Get("totalSupply")) + 1000); return(true); }
public static bool initToken(byte[] addr) { if (addr.Length != 20) { throw new InvalidOperationException("The parameter addr SHOULD be 20-byte addresses."); } //check SAR if (!checkState(SAR_STATE)) { throw new InvalidOperationException("The sar state MUST be pause."); } var key = getSARKey(addr); byte[] sar = Storage.Get(Storage.CurrentContext, key); if (sar.Length == 0) { throw new InvalidOperationException("The sar must not be null."); } SARInfo info = (SARInfo)Helper.Deserialize(sar); Storage.Put(Storage.CurrentContext, key, Helper.Serialize(info)); var txid = ((Transaction)ExecutionEngine.ScriptContainer).Hash; Operated(info.name.AsByteArray(), addr, info.txid, txid, (int)ConfigTranType.TRANSACTION_TYPE_INIT, 0); Nep55Operated(info.name.AsByteArray(), addr, info.txid, info.anchor.AsByteArray(), info.symbol.AsByteArray(), info.decimals); return(true); }
public static bool PayInterstOrPrincipal(string bondName, byte[] account) { if (!validateBond(bondName)) { return(false); } byte[] investorKey = bondInvestorPrefix.Concat(bondName.AsByteArray()).Concat(account); BigInteger balance = Storage.Get(Storage.CurrentContext, investorKey).AsBigInteger(); if (balance < minInvestCap) { return(false); } BondItem bond = (BondItem)Helper.Deserialize(GetBond(bondName)); byte[] paidKey = bondPaidPrefix.Concat(bondName.AsByteArray()).Concat(account); BigInteger paidRound = Storage.Get(Storage.CurrentContext, paidKey).AsBigInteger(); BigInteger currentRound = (Runtime.Time - bond.purchaseEndTime) / bond.Interval; if (paidRound > bond.Round) { return(false); } if (currentRound > bond.Round) { currentRound = bond.Round; } BigInteger investValue = Storage.Get(Storage.CurrentContext, investorKey).AsBigInteger(); BigInteger interst = (currentRound - paidRound) * (investValue * bond.CouponRate / 100); byte[] ret; if (currentRound == bond.Round) { ret = Native.Invoke(0, ontAddr, "transfer", new object[1] { new Transfer { From = bond.Account, To = account, Value = (ulong)(interst + investValue) } }); } else { ret = Native.Invoke(0, ontAddr, "transfer", new object[1] { new Transfer { From = bond.Account, To = account, Value = (ulong)interst } }); } if (ret[0] != 1) { return(false); } Storage.Put(Storage.CurrentContext, paidKey, paidRound + 1); return(true); }
public static Wallet getWallet(byte[] walletId) { byte[] walletBs = Storage.Get(Storage.CurrentContext, WalletsPrefix.Concat(walletId)); if (walletBs.Length == 0) { return(new Wallet()); } return((Wallet)Helper.Deserialize(walletBs)); }
public static TransferInfo getTXInfo(byte[] txid) { byte[] v = Storage.Get(Storage.CurrentContext, txid); if (v.Length == 0) { return(null); } return(Helper.Deserialize(v) as TransferInfo); }
private static SARTransferDetail getSARTxInfo(byte[] txid) { byte[] v = Storage.Get(Storage.CurrentContext, getTxidKey(txid)); if (v.Length == 0) { return(null); } return((SARTransferDetail)Helper.Deserialize(v)); }
/** * 获取时装结构 */ private static object[] _getDressInfo(byte[] dressId) { byte[] v = Storage.Get(Storage.CurrentContext, dressId); if (v.Length == 0) { return(new object[0]); } return((object[])Helper.Deserialize(v)); }
/*向债仓锁定数字资产*/ public static bool Lock(byte[] addr, BigInteger value) { if (addr.Length != 20) return false; if (value == 0) return false; byte[] key = addr.Concat(ConvertN(0)); byte[] cdp = Storage.Get(Storage.CurrentContext, key); if (cdp.Length == 0) return false; byte[] to = Storage.Get(Storage.CurrentContext, STORAGE_ACCOUNT); if (to.Length == 0) return false; object[] arg = new object[3]; arg[0] = addr; arg[1] = to; arg[2] = value; if (!(bool)SDTContract("transfer", arg)) return false; var txid = ((Transaction)ExecutionEngine.ScriptContainer).Hash; //object[] obj = new object[1]; //obj[0] = txid; //TransferInfo transferInfo = (TransferInfo)SDTContract("getTXInfo", obj); /*校验交易信息*/ //if (transferInfo.from != addr || transferInfo.to != to || value != transferInfo.value) return false; byte[] used = Storage.Get(Storage.CurrentContext, txid); /*判断txid是否已被使用*/ if (used.Length != 0) return false; CDPTransferInfo cdpInfo = (CDPTransferInfo)Helper.Deserialize(cdp); cdpInfo.locked = cdpInfo.locked + value; BigInteger currLock = cdpInfo.locked; Storage.Put(Storage.CurrentContext, key, Helper.Serialize(cdpInfo)); //记录交易详细数据 CDPTransferDetail detail = new CDPTransferDetail(); detail.from = addr; detail.cdpTxid = cdpInfo.txid; detail.type = (int)ConfigTranType.TRANSACTION_TYPE_LOCK; detail.operated = value; detail.hasLocked = currLock; detail.hasDrawed = cdpInfo.hasDrawed; detail.txid = txid; Storage.Put(Storage.CurrentContext, txid, Helper.Serialize(detail)); /*记录txid 已被使用*/ Storage.Put(Storage.CurrentContext, txid, addr); return true; }
public static BigInteger GetMaxUID() { byte[] data = Storage.Get(Storage.CurrentContext, Const.PxMaxUID); if (data == null || data.Length < 1) { return(0); } return((BigInteger)Helper.Deserialize(data)); }
public static Config getStructConfig() { byte[] value = Storage.Get(Storage.CurrentContext, GetConfigKey("structConfig".AsByteArray())); if (value.Length > 0) { return(Helper.Deserialize(value) as Config); } return(new Config()); }
// 根据其他账户的售卖挂单,进行交易 private static bool CancleSale(byte[] from, BigInteger sid) { //Check parameters if (from.Length != 20) { throw new InvalidOperationException("The parameters from and to SHOULD be 20-byte addresses."); } if (!Runtime.CheckWitness(from)) //0.2 { return(false); } StorageMap saleMul = Storage.CurrentContext.CreateMap(nameof(saleMul)); byte[] smFrom = saleMul.Get(from); // 如果from名下没有任何售卖单返回错误 if (smFrom == null || smFrom.Length == 0) { CancleMulSaleErr(from, sid, 10013); return(false); } Map <BigInteger, SaleMulInfo> sitems = Helper.Deserialize(smFrom) as Map <BigInteger, SaleMulInfo>; // 如果from名下没有该单号返回错误 if (!sitems.HasKey(sid)) { CancleMulSaleErr(from, sid, 10013); return(false); } SaleMulInfo s = sitems[sid]; object[] objs = new object[12]; objs[0] = ExecutionEngine.ExecutingScriptHash; objs[1] = from; objs[2] = s.count; for (int i = 0; i < s.count; i++) { objs[i + 3] = s.ids[i]; } // -----------调用EasyNFT 转移资产 if (NFTtransfer("transfer", objs) == false) { throw new Exception("NFTtransfer Fail!"); } //---------- // 删除该挂单 sitems.Remove(sid); saleMul.Put(from, Helper.Serialize(sitems)); CancleMulSaled(from, sid); return(true); }
public static User GetUser(byte[] addr) { byte[] key = Const.PxUser.AsByteArray().Concat(addr); byte[] bytes = Storage.Get(Storage.CurrentContext, key); if (bytes == null || bytes.Length < 1) { return(null); } return((User)Helper.Deserialize(bytes)); }
public static object[] GetTransactionInfoAsObjects(byte[] id) { byte[] bytes = Storage.Get(Storage.CurrentContext, id); if (bytes.Length == 0) { return(new object[0]); } return((object[])Helper.Deserialize(bytes)); }
/// <summary> /// Get skill weapon attribute configuration parameters /// </summary> public static object[] GetAttrConfigAsObjects() { byte[] bytes = Storage.Get(Storage.CurrentContext, Keys.AttributeConfig); if (bytes.Length == 0) { return(new object[0]); } return((object[])Helper.Deserialize(bytes)); }