requireRecipient Function
The function is declared in action.ts in asm-chain as follows:
function requireRecipient(name: Name): void
The requireRecipient function is used to notify other contracts that this contract has called a certain action, which is the action where requireRecipient is called. If the notified contract has the same action, then this action will be called.
The following sender and receiver code demonstrates how to send a notification from one contract to another.
// 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}!`);
}
}
Let's explain the code:
- The
sendercontract code is deployed in thealicecontract account. Thesayhelloaction in it calls therequireRecipientfunction to notify thehelloaccount that it has called thesayhelloaction. - The
receivercontract code is deployed in thehelloaccount. From the following code, the line#[chain(action="test", notify)]is different from the normal action code. Thenotifyparameter indicates that this action is used to receive notifications from other contracts. For an action that receives notifications, itsself.receiverandself.first_receiverare not the same. In this case,self.first_receiveris thealiceaccount andself.receiverishello. You can view the output ofchain_println!(self.receiver, self.first_receiver);during the test run to know this.
@action("sayhello", notify)
sayHello(name: Name): void {
print(`notify: hello ${name}!`);
}
Below is the test code:
@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()
Compilation:
cd examples/notify
yarn
yarn build
Testing:
ipyeos -m pytest -s -x test.py -k test_notify
Output:
[(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 =====================