Photo by Olav Ahrens Røtne on Unsplash
Solidity x Ralph - AlphWallet
Exploration of Ralph, new smart contract language powered by Alephium
In this article, we're using 0xNekr's X thread which explains how to write a smart contract that emulates a wallet, in Ralph, a smart contract language developed by Alephium.
0You can find his detailed article here: https://explorations-blockchain.com/2023/10/06/conception-dun-contrat-wallet-un-contrat-pour-gerer-vos-ethers/
Please note that this code is not intended for production use.
The contract
Fields
First, we'll define the contract fields (state), including the owner of the "wallet" and the balance. The balance will represent the current amount of $ALPH. To save on gas fees, we'll use a variable to track the $ALPH balance instead of tokenRemaining!().
Error codes
Next, we'll initialize the smart contract, but before that, we need to define the possible errors. The only error here is "InvalidCaller," which occurs if someone other than the owner tries to call the "withdraw()" function (explained later).
Withdraw
Now, things get interesting. Alephium uses annotations to enhance the security of assets (such as ALPH or other tokens) within the contract:
"assetsInContract" allows us to use the assets, specifically ALPH in this case.
"updateFields" is used as we update the contract state, specifically the balance.
"checkExternalCaller" is essential to ensure that only the owner can withdraw funds
And as we saw we are checking that the person who called the address is the owner. If not the error codes defined before will be used
Receive
The "receive" function enables the wallet owner to receive $ALPH. In this case, we also use annotations, although we don't check the caller because anyone can send $ALPH to this address.
The "PreapprovedAssets" annotation signifies that this smart contract utilizes assets, particularly ALPH. It's worth noting that this annotation introduces the concept of the Asset Permission System (APS), which will be explained in a future thread.
Conclusion
This smart contract is quite straightforward and serves to illustrate the similarities and differences between Ralph and Solidity. You can find a side-by-side comparison on our Github: https://github.com/notrustverify/solidity-ralph/blob/main/alphWallet/README.md#side-by-side
Special thanks to 0xNekr and their thread for the inspiration: https://twitter.com/0xNekr/status/1711766545959903526.
If you want to know more about Ralph and Alephium your journey will start here
Stay tuned for our next article, which will dive into APS and TxScript
For those who want to read the code, it's hosted on Github: https://github.com/notrustverify/solidity-ralph/tree/main/alphWallet
Sources: