跳转至

requireRecipient 函数

函数在asm-chain中的action.ts中的声明如下:

function requireRecipient(name: Name): void

requireRecipient函数用来通知其它合约本合约调用了某个action,这个action即是调用requireRecipient所在的action. 如果被通知的合约有相同的action,那么这个action将被调用。

以下的sender, receiver的代码演示了如何从一个合约发送通知到另一个合约。

// sender
import {
    print,
    requireAuth,
    requireRecipient,

    Name,
    Contract,
} from "asm-chain";

@contract
class MyContract extends Contract {
    @action("sayhello")
    sayHello(name: Name): void {
        print(`hello ${name}!`);
        requireAuth(name);
        requireRecipient(Name.fromString('hello'));
    }
}
//receiver.ts
import {
    Name,
    Contract,

    print,
} from "asm-chain";

@contract
class MyContract extends Contract {
    @action("sayhello", notify)
    sayHello(name: Name): void {
        print(`notify: hello ${name}!`);
    }
}

解释下代码:

  • sender合约代码部署在alice这个合约账号中,其中的sayhelloaction调用了requireRecipient这个函数来通知hello这个账号自己调用了sayhello这个action
  • receiver合约代码部署在hello这个账号中,从其中如下所示的代码,#[chain(action="sayhello", notify)]这行代码与正常的action代码不同,其中的notify参数表示这个action是用来接收其它合约通知的。用于接收通知的action,其self.receiverself.first_receiver是不相同的,在本例中,self.first_receiver为账号aliceself.receiverhello,可以在运行测试时查看chain_println!(self.receiver, self.first_receiver);的输出即可知道。
@action("sayhello", notify)
sayHello(name: Name): void {
    print(`notify: hello ${name}!`);
}

以下是测试代码:

@chain_test
def test_notify(tester):
    deploy_contracts(tester)
    args = {'name': 'alice'}
    r = tester.push_action('alice', 'sayhello', args, {'alice': 'active'})
    logger.info('++++++elapsed: %s', r['elapsed'])
    tester.produce_block()

编译:

cd examples/notify
yarn
yarn build

测试:

ipyeos -m pytest -s -x test.py -k test_notify

输出:

[(alice,sayhello)->alice]: CONSOLE OUTPUT BEGIN =====================
hello alice!
[(alice,sayhello)->alice]: CONSOLE OUTPUT END   =====================
[(alice,sayhello)->hello]: CONSOLE OUTPUT BEGIN =====================
notify: hello alice!
[(alice,sayhello)->hello]: CONSOLE OUTPUT END   =====================

示例代码

评论