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
这个合约账号中,其中的sayhello
action调用了requireRecipient
这个函数来通知hello
这个账号自己调用了sayhello
这个actionreceiver
合约代码部署在hello
这个账号中,从其中如下所示的代码,#[chain(action="sayhello", notify)]
这行代码与正常的action代码不同,其中的notify
参数表示这个action是用来接收其它合约通知的。用于接收通知的action,其self.receiver
和self.first_receiver
是不相同的,在本例中,self.first_receiver
为账号alice
,self.receiver
为hello
,可以在运行测试时查看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 =====================