Examples
An extensive collection of examples is available in the GitHub repository. Below we discuss a few of these examples in more details. These examples focus mainly on the use of the SDK, while the Examples page in the language section focuses more on the NexScript syntax.
Transfer With Timeout
The idea of this smart contract is explained on the Language Examples page. The gist is that it allows you to send an amount of NEXA to someone, but if they don't claim the sent amount, it can be recovered by the sender.
contract TransferWithTimeout(pubkey sender, pubkey recipient, int timeout) {
function transfer(sig recipientSig) {
require(checkSig(recipientSig, recipient));
}
function timeout(sig senderSig) {
require(checkSig(senderSig, sender));
require(tx.time >= timeout);
}
}
Now to put this smart contract in use in a JavaScript application we have to use the NexScript SDK in combination with a Nexa library such as NexCore. This library is used to generate public/private keys for the contract participants. Then these keys can be used in the NexScript SDK. The key generation code is left out of this example.
import { Contract, SignatureTemplate } from '@nexscript/nexscript';
import { alicePriv, alicePub, bobPriv, bobPub } from './somewhere.js';
import artifact from './transfer_with_timeout.json';
// Instantiate a new contract using the artifact and constructor arguments:
// { sender: alicePub, recipient: bobPub, timeout: 1000000 }
// No network provider is provided, so the default ElectrumNetworkProvider is used
const contract = new Contract(artifact, [alicePub, bobPub, 1000000n]);
// Display contract address and balance
console.log('contract address:', contract.address);
console.log('contract balance:', await contract.getBalance());
// Call the transfer function with Bob's signature
// i.e. Bob claims the money that Alice has sent him
const txDetails = await contract.functions
.transfer(new SignatureTemplate(bobPriv))
.to('nexa:nqtsq5g537fcf6z85pgwk4my5e5ddmypa2sm47mkzavt6zky', 10000n)
.send();
console.log(txDetails);
// Call the timeout function with Alice's signature
// i.e. Alice recovers the money that Bob has not claimed
// But because the timeout has not passed yet, the function fails and
// we call the meep function so the transaction can be debugged instead
const meepStr = await contract.functions
.timeout(new SignatureTemplate(alicePriv))
.to('nexa:nqtsq5g5wtkt44pfqusjj3wulk2n2pd27lhpzg0m326kcnsj', 10000n)
.meep();
console.log(meepStr);