Skip to content

Instantly share code, notes, and snippets.

@glasgowm148
Created July 27, 2023 11:38
Show Gist options
  • Save glasgowm148/b452f22f1e7d082d74f59030509d3924 to your computer and use it in GitHub Desktop.
Save glasgowm148/b452f22f1e7d082d74f59030509d3924 to your computer and use it in GitHub Desktop.
import org.ergoplatform.compiler.ErgoScalaCompiler._
import org.ergoplatform.playgroundenv.utils.ErgoScriptCompiler
import org.ergoplatform.playground._
val blockchainSim = newBlockChainSimulationScenario("FundLock Scenario")
val nanoergsInErg = 1000000000L
val alice = blockchainSim.newParty("Alice")
val aliceFunds = 200*nanoergsInErg
val bob = blockchainSim.newParty("Bob")
val depositAmount = 100*nanoergsInErg
alice.generateUnspentBoxes(toSpend = aliceFunds)
alice.printUnspentAssets()
bob.printUnspentAssets()
println("---------------------")
///////////////////////////////////////////
// FundLock Contract //
///////////////////////////////////////////
// The fund lock contract allows Bob to withdraw the funds after a certain deadline.
// Before the deadline, the funds are locked and cannot be accessed by anyone.
val fundLockScript = s""" HEIGHT > deadline && bobPK """.stripMargin
val unlockTime = blockchainSim.getHeight + 500
val fundLockContract = ErgoScriptCompiler.compile(Map("deadline" -> unlockTime,
"bobPK" -> bob.wallet.getAddress.pubKey),
fundLockScript)
val fundLockBox = Box(value = depositAmount, script = fundLockContract)
val fundLockTransaction = Transaction(
inputs = alice.selectUnspentBoxes(toSpend = aliceFunds),
outputs = List(fundLockBox),
fee = MinTxFee,
sendChangeTo = alice.wallet.getAddress
)
println(fundLockTransaction)
println("---------------------")
val fundLockTransactionSigned = alice.wallet.sign(fundLockTransaction)
blockchainSim.send(fundLockTransactionSigned)
alice.printUnspentAssets()
println("---------------------")
println("===== Bob withdraws the funds after deadline =====")
blockchainSim.setHeight(unlockTime + 1)
val bobWithdrawBox = Box(value = depositAmount - MinTxFee,
script = contract(bob.wallet.getAddress.pubKey))
val bobWithdrawTransaction = Transaction(
inputs = List(fundLockTransactionSigned.outputs(0)),
outputs = List(bobWithdrawBox),
fee = MinTxFee,
sendChangeTo = bob.wallet.getAddress
)
val bobWithdrawTransactionSigned = bob.wallet.sign(bobWithdrawTransaction)
blockchainSim.send(bobWithdrawTransactionSigned)
alice.printUnspentAssets()
bob.printUnspentAssets()
println("---------------------")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment