Type
TRANSFER
Validation date
2023-11-30 17:22:02 UTC
Fee
0 UCO

Code (3.89 KB)

@version 1

####################################
# EVM => Archethic : Request funds #
####################################

condition triggered_by: transaction, on: request_funds(end_time, amount, user_address, secret_hash, evm_tx_address, evm_contract, chain_id), as: [
  type: "contract",
  code: valid_chargeable_code?(end_time, amount, user_address, secret_hash),
  timestamp: (
    # End time cannot be less than now or more than 1 day
    now = Time.now()
    end_time > now && end_time <= now + 86400
  ),
  uco_transfers: (
    # Ensure the pool has enough UCO to send the requested fund
    balance = Chain.get_uco_balance(contract.address)
    balance >= amount
  ),
  content: List.in?([11155111,80001,97], chain_id),
  token_transfers: !contract_already_charged?(Json.parse(contract.content), chain_id, evm_contract),
  address: (
    valid? = false

    tx_receipt_request = get_tx_receipt_request(evm_tx_address)
    call_status_request = get_call_request(evm_contract, "status()", 2)
    call_enough_funds_request = get_call_request(evm_contract, "enoughFunds()", 3)
    call_hash_request = get_call_request(evm_contract, "hash()", 4)
    call_end_time_request = get_call_request(evm_contract, "lockTime()", 5)
    call_amount_request = get_call_request(evm_contract, "amount()", 6)

    body = Json.to_string([
      tx_receipt_request,
      call_status_request,
      call_enough_funds_request,
      call_hash_request,
      call_end_time_request,
      call_amount_request
    ])

    chain_data = get_chain_data(chain_id)
    headers = ["Content-Type": "application/json"]

    res = Http.request(chain_data.endpoint, "POST", headers, body)
    if res.status == 200 && Json.is_valid?(res.body) do
      responses = Json.parse(res.body)

      tx_receipt = get_response(responses, 1)
      call_status = get_response(responses, 2)
      call_enough_funds = get_response(responses, 3)
      call_hash = get_response(responses, 4)
      call_end_time = get_response(responses, 5)
      call_amount = get_response(responses, 6)

      if !any_nil?([tx_receipt, call_status, call_enough_funds, call_hash, call_end_time, call_amount]) do
        # event = Crypto.hash("ContractMinted(address,uint256)", "keccak256")
        event = "0x8640c3cb3cba5653efe5a3766dc7a9fb9b02102a9f97fbe9ea39f0082c3bf497"
        valid_tx_receipt? = valid_tx_receipt?(tx_receipt, chain_data.proxy_address, evm_contract, event)
        # Pending is status 0
        valid_status? = valid_status?(call_status, 0)
        enough_funds? = enough_funds?(call_enough_funds)
        valid_hash? = valid_hash?(call_hash, secret_hash)
        valid_end_time? = valid_end_time?(call_end_time, end_time)
        valid_amount? = valid_amount?(call_amount, amount, chain_data.decimals)

        valid? = valid_tx_receipt? && valid_status? && enough_funds? && valid_hash? && valid_end_time? && valid_amount?
      end
    end

    valid?
  )
]

actions triggered_by: transaction, on: request_funds(end_time, amount, _, _, _, evm_contract, chain_id) do
  chain_data = get_chain_data(chain_id)

  contract_content = Json.parse(contract.content)

  # Delete old contract where end_time is over
  charged_contracts = Map.get(contract_content, "charged_contracts", Map.new())
  charged_contracts = delete_old_charged_contracts(charged_contracts)

  # Update state to keep contract already used
  new_charged_contracts = add_charged_contracts(charged_contracts, chain_id, evm_contract, end_time)
  contract_content = Map.set(contract_content, "charged_contracts", new_charged_contracts)

  Contract.set_content(Json.to_string(contract_content))
  Contract.set_type("transfer")
  Contract.add_recipient(
    address: transaction.address,
    action: "provision",
    args: [evm_contract, chain_data.endpoint]
  )
  Contract.add_uco_transfer(to: transaction.address, amount: amount)
end

##########################################
# Archethic => EVM : Request secret hash #
##########################################

condition triggered_by: transaction, on: request_secret_hash(htlc_genesis_address, amount, user_address, chain_id), as: [
  type: "transfer",
  code: valid_signed_code?(htlc_genesis_address, amount, user_address),
  previous_public_key:
    (
      # Ensure contract has enough fund to withdraw
      previous_address = Chain.get_previous_address()
      balance = Chain.get_uco_balance(previous_address)
      balance >= amount
    ),
  content: List.in?([11155111,80001,97], chain_id),
  uco_transfers:
    (
      htlc_genesis_address = String.to_hex(htlc_genesis_address)
      Map.get(htlc_genesis_address) == amount
    )
]

actions triggered_by: transaction, on: request_secret_hash(htlc_genesis_address, amount, _user_address, chain_id) do
  # Here delete old secret that hasn't been used before endTime
  contract_content = Json.parse(contract.content)

  requested_secrets = Map.get(contract_content, "requested_secrets", Map.new())
  requested_secrets = delete_unused_secrets(requested_secrets)

  secret = Crypto.hmac(transaction.address)
  secret_hash = Crypto.hash(secret, "sha256")

  # Build signature for EVM decryption
  signature = sign_for_evm(secret_hash, chain_id)

  # Calculate endtime now + 2 hours
  now = Time.now()
  end_time = now - Math.rem(now, 60) + 7200

  # Add secret and signature in content
  htlc_map = [
    hmac_address: transaction.address,
    end_time: end_time,
    chain_id: chain_id
  ]

  htlc_genesis_address = String.to_hex(htlc_genesis_address)
  new_requested_secrest = Map.set(requested_secrets, htlc_genesis_address, htlc_map)
  contract_content = Map.set(contract_content, "requested_secrets", new_requested_secrest)

  Contract.set_content(Json.to_string(contract_content))

  Contract.add_recipient(
    address: htlc_genesis_address,
    action: "set_secret_hash",
    args: [secret_hash, signature, end_time]
  )
end

####################################
# Archethic => EVM : Reveal secret #
####################################

condition triggered_by: transaction, on: reveal_secret(htlc_genesis_address, evm_tx_address, evm_contract), as: [
  type: "transfer",
  content: (
    # Ensure htlc_genesis_address exists in pool state
    # and end_time has not been reached
    valid? = false

    contract_content = Json.parse(contract.content)

    htlc_genesis_address = String.to_hex(htlc_genesis_address)
    requested_secrets = Map.get(contract_content, "requested_secrets", Map.new())
    htlc_map = Map.get(requested_secrets, htlc_genesis_address)

    if htlc_map != nil do
      valid? = htlc_map.end_time > Time.now()
    end

    valid?
  ),
  address: (
    valid? = false
    htlc_map = nil

    contract_content = Json.parse(contract.content)

    htlc_genesis_address = String.to_hex(htlc_genesis_address)
    requested_secrets = Map.get(contract_content, "requested_secrets", Map.new())
    htlc_map = Map.get(requested_secrets, htlc_genesis_address)

    if htlc_map != nil do
      tx_receipt_request = get_tx_receipt_request(evm_tx_address)
      call_status_request = get_call_request(evm_contract, "status()", 2)
      call_enough_funds_request = get_call_request(evm_contract, "enoughFunds()", 3)
      call_hash_request = get_call_request(evm_contract, "hash()", 4)
      call_end_time_request = get_call_request(evm_contract, "lockTime()", 5)
      call_amount_request = get_call_request(evm_contract, "amount()", 6)

      body = Json.to_string([
        tx_receipt_request,
        call_status_request,
        call_enough_funds_request,
        call_hash_request,
        call_end_time_request,
        call_amount_request
      ])

      chain_data = get_chain_data(htlc_map.chain_id)
      headers = ["Content-Type": "application/json"]

      res = Http.request(chain_data.endpoint, "POST", headers, body)
      if res.status == 200 && Json.is_valid?(res.body) do
        responses = Json.parse(res.body)

        tx_receipt = get_response(responses, 1)
        call_status = get_response(responses, 2)
        call_enough_funds = get_response(responses, 3)
        call_hash = get_response(responses, 4)
        call_end_time = get_response(responses, 5)
        call_amount = get_response(responses, 6)

        if !any_nil?([tx_receipt, call_status, call_enough_funds, call_hash, call_end_time, call_amount]) do
          # event = Crypto.hash("ContractProvisioned(address,uint256)", "keccak256")
          event = "0x0c5d1829e93110ff9c24aa8ac41893b65509108384b3036d4f73ffccb235e9ec"

          secret = Crypto.hmac(htlc_map.hmac_address)
          secret_hash = Crypto.hash(secret, "sha256")

          htlc_data = Contract.call_function(htlc_genesis_address, "get_htlc_data", [])

          valid_tx_receipt? = valid_tx_receipt?(tx_receipt, chain_data.proxy_address, evm_contract, event)
          # Pending is status 0
          valid_status? = valid_status?(call_status, 0)
          enough_funds? = enough_funds?(call_enough_funds)
          valid_hash? = valid_hash?(call_hash, secret_hash)
          valid_end_time? = valid_end_time?(call_end_time, htlc_map.end_time)
          valid_amount? = valid_amount?(call_amount, htlc_data.amount, chain_data.decimals)

          valid? = valid_tx_receipt? && valid_status? && enough_funds? && valid_hash? && valid_end_time? && valid_amount?
        end
      end
    end

    valid?
  )
]

actions triggered_by: transaction, on: reveal_secret(htlc_genesis_address, _evm_tx_address, _evm_contract) do
  contract_content = Json.parse(contract.content)
  requested_secrets = Map.get(contract_content, "requested_secrets", Map.new())

  htlc_genesis_address = String.to_hex(htlc_genesis_address)
  htlc_map = Map.get(requested_secrets, htlc_genesis_address)

  requested_secrets = Map.delete(requested_secrets, htlc_genesis_address)
  contract_content = Map.set(contract_content, "requested_secrets", requested_secrets)

  secret = Crypto.hmac(htlc_map.hmac_address)
  # Do not use chain ID in signature for the secret reveal
  signature = sign_for_evm(secret, nil)

  Contract.set_content(Json.to_string(contract_content))

  Contract.add_recipient(
    address: htlc_genesis_address,
    action: "reveal_secret",
    args: [secret, signature]
  )
end

condition triggered_by: transaction, on: update_code(new_code), as: [
  previous_public_key:
    (
      # Pool code can only be updated from the master chain if the bridge

      # Transaction is not yet validated so we need to use previous address
      # to get the genesis address
      previous_address = Chain.get_previous_address()
      Chain.get_genesis_address(previous_address) == 0x000020a6911478356ca264174e35d26021fb4cbe870703bb7c3859e01cdb34bcd823
    ),
  code: Code.is_valid?(new_code)
]

actions triggered_by: transaction, on: update_code(new_code) do
  Contract.set_type("contract")
  # Keep contract state
  Contract.set_content(contract.content)
  Contract.set_code(new_code)
end

####################
# Public functions #
####################

export fun get_token_address() do
  "UCO"
end

#####################
# Private functions #
#####################

fun contract_already_charged?(content, chain_id, evm_contract) do
  chain_id = String.from_number(chain_id)
  evm_contract = String.to_lowercase(evm_contract)

  charged_contracts = Map.get(content, "charged_contracts", Map.new())
  contracts = Map.get(charged_contracts, chain_id, Map.new())

  Map.get(contracts, evm_contract, nil) != nil
end

fun add_charged_contracts(charged_contracts, chain_id, evm_contract, end_time) do
  chain_id = String.from_number(chain_id)
  evm_contract = String.to_lowercase(evm_contract)

  contracts = Map.get(charged_contracts, chain_id, Map.new())
  updated_contracts = Map.set(contracts, evm_contract, end_time)

  Map.set(charged_contracts, chain_id, updated_contracts)
end

fun delete_old_charged_contracts(charged_contracts) do
  now = Time.now()
  for chain_id in Map.keys(charged_contracts) do
    contracts = Map.get(charged_contracts, chain_id)

    for address in Map.keys(contracts) do
      contract_end_time = Map.get(contracts, address)
      if contract_end_time <= now do
        contracts = Map.delete(contracts, address)
      end
    end

    charged_contracts = Map.set(charged_contracts, chain_id, contracts)
  end

  charged_contracts
end

fun delete_unused_secrets(requested_secrets) do
  for address in Map.keys(requested_secrets) do
    htlc_map = Map.get(requested_secrets, address)

    if htlc_map.end_time <= Time.now() do
      requested_secrets = Map.delete(requested_secrets, address)
    end
  end

  requested_secrets
end

fun valid_chargeable_code?(end_time, amount, user_address, secret_hash) do
  args = [
    end_time,
    user_address,
    0x000018d60115ece0c7558a46b4693749bf6beab524fddccf9b10b910619e4ee08801,
    secret_hash,
    "UCO",
    amount
  ]

  expected_code = Contract.call_function(0x0000795bfd6ca2f5ea9f378c20775caf798e9bfbff6aec94bf87ad8d59233b4fa299, "get_chargeable_htlc", args)

  Code.is_same?(expected_code, transaction.code)
end

fun valid_signed_code?(htlc_address, amount, user_address) do
  valid? = false

  htlc_address = String.to_hex(htlc_address)
  last_htlc_transaction = Chain.get_last_transaction(htlc_address)

  if last_htlc_transaction != nil do
    args = [
      user_address,
      0x000018d60115ece0c7558a46b4693749bf6beab524fddccf9b10b910619e4ee08801,
      "UCO",
      amount
    ]

    expected_code = Contract.call_function(0x0000795bfd6ca2f5ea9f378c20775caf798e9bfbff6aec94bf87ad8d59233b4fa299, "get_signed_htlc", args)

    valid? = Code.is_same?(expected_code, last_htlc_transaction.code)
  end

  valid?
end

fun get_chain_data(chain_id) do
  data = Map.new()
  
  if chain_id == 11155111 do
    data = Map.set(data, "endpoint", "https://sepolia.infura.io/v3/3a7a2dbdbec046a4961550ddf8c7d78a")
    data = Map.set(data, "proxy_address", "0x50b8b73327613468e5605ed59b980555daac354a")
    data = Map.set(data, "decimals", 18)
  end

  if chain_id == 80001 do
    data = Map.set(data, "endpoint", "https://polygon-mumbai.infura.io/v3/3a7a2dbdbec046a4961550ddf8c7d78a")
    data = Map.set(data, "proxy_address", "0xe55915d112711127339f073e75185e6311dd72c8")
    data = Map.set(data, "decimals", 18)
  end

  if chain_id == 97 do
    data = Map.set(data, "endpoint", "https://data-seed-prebsc-1-s2.bnbchain.org:8545")
    data = Map.set(data, "proxy_address", "0xacc408cb6d6d9c73c6003269d322cb78150fc137")
    data = Map.set(data, "decimals", 18)
  end

  data
end

fun get_call_request(evm_contract, call, id) do
  abi_data = Evm.abi_encode(call)
  tx = [to: evm_contract, data: "0x#{abi_data}"]
  [jsonrpc: "2.0", id: id, method: "eth_call", params: [tx, "latest"]]
end

fun get_response(responses, id) do
  response = nil
  for res in responses do
    if res.id == id do
      response = Map.get(res, "result")
    end
  end
  response
end

fun any_nil?(list) do
  nil? = false
  for i in list do
    if i == nil do
      nil? = true
    end
  end
  nil?
end

fun get_tx_receipt_request(evm_tx_address) do
  [
    jsonrpc: "2.0",
    id: 1,
    method: "eth_getTransactionReceipt",
    params: [evm_tx_address]
  ]
end

fun valid_tx_receipt?(tx_receipt, proxy_address, evm_contract, expected_event) do
  logs = nil
  for log in tx_receipt.logs do
    if String.to_lowercase(log.address) == proxy_address do
      logs = log
    end
  end

  if logs != nil do
    # Transaction is valid
    valid_status? = tx_receipt.status == "0x1"
    # Transaction interacted with proxy address
    valid_proxy_address? = String.to_lowercase(tx_receipt.to) == proxy_address
    # Logs are comming from proxy address
    valid_logs_address? = String.to_lowercase(logs.address) == proxy_address
    # Pool contract emmited expected event
    event = List.at(logs.topics, 0)
    valid_event? = String.to_lowercase(event) == expected_event
    # Contract minted match evm_contract in parameters
    decoded_data = Evm.abi_decode("(address)", List.at(logs.topics, 1))
    topic_address = List.at(decoded_data, 0)
    valid_contract_address? = topic_address == String.to_lowercase(evm_contract)
    
    valid_status? && valid_proxy_address? && valid_logs_address? && valid_event? && valid_contract_address?
  else
    false
  end
end

fun valid_status?(call_status, expected_status) do
  decoded_data = Evm.abi_decode("(uint)", call_status)
  List.at(decoded_data, 0) == expected_status
end

fun enough_funds?(call_enough_funds) do
  decoded_data = Evm.abi_decode("(bool)", call_enough_funds)
  List.at(decoded_data, 0) == true
end

fun valid_hash?(call_hash, secret_hash) do
  secret_hash = "0x#{String.to_lowercase(secret_hash)}"
  decoded_data = Evm.abi_decode("(bytes32)", call_hash)
  List.at(decoded_data, 0) == secret_hash
end

fun valid_end_time?(call_end_time, end_time) do
  decoded_data = Evm.abi_decode("(uint256)", call_end_time)
  List.at(decoded_data, 0) == end_time
end

fun valid_amount?(call_amount, amount, decimals) do
  decoded_data = Evm.abi_decode("(uint256)", call_amount)
  big_int_amount = List.at(decoded_data, 0)
  decimal_amount = big_int_amount / Math.pow(10, decimals)
  decimal_amount == amount
end

fun sign_for_evm(data, chain_id) do
  hash = data

  if chain_id != nil do
    # Perform a first hash to combine data and chain_id
    abi_data = Evm.abi_encode("(bytes32,uint)", [data, chain_id])
    hash = Crypto.hash(abi_data, "keccak256")
  end

  prefix = String.to_hex("\x19Ethereum Signed Message:\n32")
  signature_payload = Crypto.hash("#{prefix}#{hash}", "keccak256")

  sig = Crypto.sign_with_recovery(signature_payload)

  if sig.v == 0 do
    sig = Map.set(sig, "v", 27)
  else
    sig = Map.set(sig, "v", 28)
  end

  sig
end

Content (1.03 KB)

{
  "charged_contracts": {
    "11155111": {
      "0x78bcf40d3e6ceef19c034c9f3cf8658375125538": 1701371280
    },
    "80001": {
      "0x23f78217cce85b531020575b51025cfc8d5e9a00": 1701370020,
      "0x85e7de93879f67cb9b173ed1766da9a3ab253f6d": 1701372060,
      "0x860d3412a21480bcd87fa6ac602720b928d00a2c": 1701368640,
      "0x8667d4c08501f1501465d04ce5f83855af36be92": 1701366900,
      "0x868f764cc65c669dbb0e177075c624151bb16e16": 1701365520,
      "0x9ad08147d9767b270f156aba43cfe6ad4dd1466d": 1701367980
    },
    "97": {}
  },
  "requested_secrets": {
    "00001A482857D470C524EABF831A333E0B9C7BDC233471B32128BB073C0356762556": {
      "chain_id": 80001,
      "end_time": 1701369720,
      "hmac_address": "0000B8120589711367301BFD44BCAEFAF9B04020AA15B00381398A0AB567CFE2ABB4"
    },
    "0000346339D2DF4A00A45C89E84CA1A5F43D81663D31AF3ED564C25169A010011AA4": {
      "chain_id": 80001,
      "end_time": 1701369300,
      "hmac_address": "0000C2ACCAF5C2FB9F177F40E2F75A45C0C7E05C9668DAB2F0CD7367D92AA65DEA2C"
    },
    "0000AA5E389E314EA3AD8970E5894D9BB174DA897F5CD4CAA743D9B5915512882A11": {
      "chain_id": 97,
      "end_time": 1701365940,
      "hmac_address": "0000CD22C9B8C3C4A4BFF20E8D2B45C95E1F90B977E7380AE85F8EC1DE3356B5AD2E"
    }
  }
}

State (0 B)

Movements (0)

Ownerships (1)

  • Secret shared with 1 key

    Encoded secret

    9ECAA33C09E3CE4F7F6A1BD5029836E4AD153C3D7FD856A82A58EF7790793AE594A7BE092C52262CD0F199488EABEFC063A0C8007397FE6673225605

    Authorized keys

    • 00017877BCF4122095926A49489009649603AB129822A19EF9D573B8FD714911ED7F

Contract recipients (1)

Inputs (0)

Contract inputs (0)

Unspent outputs (1)

Proofs and signatures

Previous public key

00017F1E64C10C1C6A566803B78C4021ACDE93F950BDF6BF6DB5106BC0C3EC475E48

Previous signature

E9E89281C9D77A8ED9ECD472F90A37245D00413E0885F285DD2C9ACFE2005B4F37B4CBBEDAD0CEB6CC4A2AB25898FBC6762464B062ACD4779FCF29275A7D4E05

Origin signature

304502207B3773EC3A89B6C3B45D91952092C8693A8FA7066022C8D795FF6F88A988FFE4022100E88739FB5B35DE78711115E8DD444C957C6FAD5DF609C228AD51DBE79FDA7B48

Proof of work

010204B3B2A53580086B9F36919CF40ABC55904729F78BF43673E216FAC1EB2451DD1E521879C6588F0CB09B150A103A39A73E2816B5ADF51F0721348BA3A66C33023B

Proof of integrity

000FDA97F2351F76FBA1892DD4A2AB8EF81C83421A95FD1730AC9A916CBFEF0581

Coordinator signature

645E3C4A8F0722583F2A7750D6F079F40ACF04FE59254D87999744CA229B93926E42A7BD081D213C62A0D8DE9F3742EBC17E1BF6C175EC0B1B4663C500565A0C

Validator #1 public key

0001B0A94804BF8ECC9897075C6207FF63EF4D339F57A0349888E6B77CD47DB53EF3

Validator #1 signature

BDA4F8AF9402AC0881B004DF6F37365C1A668D691F2D17B6F34D0B0A02E1FC962E3EE86C3C895822C485BB26EF55E7E6FDF7EE675D57B9D1B39D36BA35A3DA06

Validator #2 public key

00011B58ED42235461734EAF253BD97A80B92899ABCC3BE680D44B6825DD2A88A947

Validator #2 signature

6EAC438427122EC73BF1E560EBE07F8CF182C6BF2031E31BE6813AAB5317287DAFBA6107C599A427EECDAA0932F13382D79051A9E069C2D645C0141EF7D88804

Validator #3 public key

000103E30584AD8DE66F9E29419D5D0ABEE5A76722C9FD0D012BDDE3A6E2B149C48D

Validator #3 signature

EB08CAF8326CE2FE434EB0D8B8D9648F77EC58CC5F5A9F7BF19B87E944F0367D29EFF143F67780C4F36035FB11BAC085D34B851CE6EAC433EA1E764C1B062908