neo-project / docs

NEO Documentation
http://docs.neo.org
Creative Commons Attribution 4.0 International
195 stars 284 forks source link

【Neo3.x】Please add some instruction on how to use NEO or GAS in contract #1083

Closed longfeiWan9 closed 3 years ago

longfeiWan9 commented 4 years ago

In Neo3, NEO and GAS will be deployed as native contract instead of being as UTXO asset. It gives the advantage to use NEO and GAS in any smart contract easier.

But for the developers who are used to Neo2, this will be a new features for Neo3. Therefore, it is better to provide a clear instruction and example on how to use NEO or GAS in any smart contract.

chenzhitong commented 4 years ago

尝试在智能合约中实现资产兑换方法,即充值NEO,获得NEP-5资产

方法1:在合约中创建 MintTokens 方法,在其中调用 Native.NEO("transfer" ……) 实现 NEO 的转账 结果:调用失败 原因:原生合约的 transfer 方法不支持跳板调用。

方法2:手动构造一笔交易,交易的 Scripts 字段包含两部分:第一部分是NEO的转账以,第二部分是调用合约的 MintTokens 方法。在合约中创建 MintTokens 方法,在方法中通过 Runtime.GetNotifications() 获得NEO转账的执行结果。

合约示例代码如下

public static byte[] NeoScriptHash = "0xde5f57d430d3dece511cf975a8d37848cb9e0525".HexToBytes();

[DisplayName("mintTokens")]
public static bool MintTokens()
{
    foreach (var notification in Runtime.GetNotifications())
    {
        if (notification.ScriptHash == NeoScriptHash)
        {
            var transferNotification = notification.State as object[];
            if (transferNotification.Length > 3 && (string)notification[0] 0= "Transfer")
            {
                var from = (byte[])transferNotification[1];
                var to = (byte[])transferNotification[2];
                var amount = (BigInteger)transferNotification[3];
                if (to.Equals(ExecutionEngine.ExecutingScriptHash))
                {
                    //其它代码
                }
            }
        }
    }
    return false;
}

结果:可能有戏,等我测完……🐸

chenzhitong commented 4 years ago

啊哈,这里有现成的代码:https://github.com/neo-project/neo-devpack-dotnet/blob/master/templates/Template.NEP5.CSharp/NEP5.Crowdsale.cs

chenzhitong commented 4 years ago

Waiting for https://github.com/neo-project/neo-devpack-dotnet/pull/304