Fungsi Bawaan

Referensi lengkap untuk semua fungsi bawaan yang tersedia dalam kebijakan

Hanya fungsi bawaan berikut yang diaktifkan dalam kebijakan. Fungsi yang tidak tercantum di sini dinonaktifkan karena alasan keamanan. Lihat Pembatasan untuk detail tentang fungsi yang dinonaktifkan.

Fungsi String

Fungsi untuk memanipulasi dan memeriksa nilai string. Penting untuk bekerja dengan alamat, nama metode, dan bidang teks lainnya.

contains

Periksa apakah string berisi substring. Mengembalikan true jika ditemukan, false jika tidak.

Contoh

# Block any method containing "sign"
deny if {
    contains(input.rpc_method, "sign")
}

startswith

Periksa apakah string dimulai dengan awalan. Berguna untuk mencocokkan kategori metode atau pola alamat.

Contoh

# Block debug methods
deny if {
    startswith(input.rpc_method, "debug_")
}
 
# Block addresses starting with many zeros
deny if {
    startswith(input.to_address, "0x00000000")
}

endswith

Periksa apakah string diakhiri dengan akhiran.

Contoh

# Block addresses ending with specific pattern
deny if {
    endswith(lower(input.to_address), "dead")
}

lower

Konversi string ke huruf kecil. Penting untuk perbandingan alamat yang tidak peka huruf besar-kecil karena alamat dapat memiliki huruf besar-kecil campuran.

Contoh

# Case-insensitive address check
blocked_addresses := {
    "0x000000000000000000000000000000000000dead"
}
 
deny if {
    lower(input.to_address) in blocked_addresses
}

upper

Konversi string ke huruf besar.

Contoh

# Normalize method names that might have inconsistent casing
deny if {
    upper(input.rpc_method) == "ETH_SENDTRANSACTION"
    input.usd_value > 10000
}

concat

Gabungkan array string dengan pembatas.

Contoh

# Join values for logging or comparison
message := concat(", ", ["chain:", input.chain, "method:", input.rpc_method])

split

Pisahkan string menjadi array menggunakan pembatas.

Contoh

# Parse a method name
parts := split(input.rpc_method, "_")
 
deny if {
    parts[0] == "debug"
}

replace

Ganti semua kemunculan substring dengan string lain.

Contoh

# Normalize address format
normalized := replace(input.to_address, "0X", "0x")

substring

Ekstrak sebagian string berdasarkan posisi awal dan panjang.

Contoh

# Get method prefix (first 4 characters after "eth_")
deny if {
    startswith(input.rpc_method, "eth_")
    method_action := substring(input.rpc_method, 4, 4)
    method_action == "send"
}

sprintf

Format string dengan placeholder. Berguna untuk membuat nilai dinamis.

PlaceholderType
%sString
%dInteger
%fFloat
%vAny value

Contoh

# Create formatted message
threshold := 10000
message := sprintf("Value %d exceeds limit of %d", [input.usd_value, threshold])

trim

Hapus karakter yang ditentukan dari kedua ujung string.

Contoh

# Remove specific characters from both ends
cleaned := trim(input.rpc_method, "_")

trim_space

Hapus spasi dari kedua ujung string.

Contoh

# Clean up input with extra spaces
clean_method := trim_space(input.rpc_method)

trim_prefix

Hapus awalan dari string jika ada.

Contoh

# Remove common prefix to get the action name
method_name := trim_prefix(input.rpc_method, "eth_")
 
deny if {
    method_name == "sendTransaction"
}

trim_suffix

Hapus akhiran dari string jika ada.

Contoh

# Remove suffix for comparison
base_method := trim_suffix(input.rpc_method, "_v2")

indexof

Temukan indeks kemunculan pertama substring. Mengembalikan -1 jika tidak ditemukan.

Contoh

# Check if underscore exists
deny if {
    indexof(input.rpc_method, "_") == -1
}

Fungsi Regex

Fungsi untuk pencocokan pola menggunakan ekspresi reguler. Lebih kuat daripada fungsi string untuk pola kompleks.

regex.match

Periksa apakah string cocok dengan pola ekspresi reguler. Mengembalikan true atau false.

Contoh

# Block methods starting with debug_, admin_, or personal_
deny if {
    regex.match("^(debug_|admin_|personal_)", input.rpc_method)
}
 
# Block addresses with many leading zeros
deny if {
    regex.match("^0x0{10,}", input.to_address)
}

regex.replace

Ganti semua kecocokan pola dengan string pengganti.

Contoh

# Remove all non-alphanumeric characters
cleaned := regex.replace(input.rpc_method, "[^a-zA-Z0-9]", "")

regex.split

Pisahkan string berdasarkan pola regex.

Contoh

# Split by multiple delimiters
parts := regex.split("[_.]", input.rpc_method)

regex.find_n

Temukan hingga n kecocokan pola dalam string.

Contoh

# Find all hex sequences
hex_matches := regex.find_n("0x[a-fA-F0-9]+", input.raw_params[0].data, 10)
 
deny if {
    count(hex_matches) > 5
}

Fungsi Waktu

Fungsi untuk bekerja dengan waktu. Semua nilai waktu dalam nanodetik sejak epoch Unix.

time.now_ns

Dapatkan waktu saat ini dalam nanodetik. Gunakan ini sebagai dasar untuk kebijakan berbasis waktu.

Contoh

# Block high-value transactions during volatile market hours
deny if {
    current := time.now_ns()
    [hour, _, _] := time.clock(current)
    hour >= 14  # After 2 PM UTC (US market open)
    hour < 21   # Before 9 PM UTC (US market close)
    input.usd_value > 50000
}

time.clock

Ekstrak jam, menit, dan detik dari timestamp. Mengembalikan [hour, minute, second].

Contoh

# Block outside business hours (9 AM - 5 PM UTC)
deny if {
    [hour, _, _] := time.clock(time.now_ns())
    hour < 9
}
 
deny if {
    [hour, _, _] := time.clock(time.now_ns())
    hour >= 17
}

time.weekday

Dapatkan hari dalam minggu dari timestamp. Mengembalikan 0 (Minggu) hingga 6 (Sabtu).

Contoh

# Block on weekends
deny if {
    day := time.weekday(time.now_ns())
    day == 0  # Sunday
}
 
deny if {
    day := time.weekday(time.now_ns())
    day == 6  # Saturday
}

time.date

Ekstrak tahun, bulan, dan hari dari timestamp. Mengembalikan [year, month, day].

Contoh

# Block on specific dates
deny if {
    [year, month, day] := time.date(time.now_ns())
    month == 12
    day == 25  # Christmas
}

time.parse_rfc3339_ns

Uraikan string timestamp berformat RFC3339 menjadi nanodetik.

Contoh

# Compare against a specific date
cutoff := time.parse_rfc3339_ns("2024-12-31T23:59:59Z")
 
deny if {
    time.now_ns() > cutoff
}

time.add_date

Tambahkan tahun, bulan, dan hari ke timestamp.

Contoh

# Block transactions if we're within 7 days of year end
deny if {
    year_end := time.parse_rfc3339_ns("2024-12-31T23:59:59Z")
    week_before := time.add_date(year_end, 0, 0, -7)
    time.now_ns() > week_before
    input.usd_value > 10000
}

time.diff

Hitung perbedaan antara dua timestamp. Mengembalikan [years, months, days, hours, minutes, seconds].

Contoh

# Check if more than 1 hour has passed
start := time.parse_rfc3339_ns("2024-01-01T00:00:00Z")
[_, _, _, hours, _, _] := time.diff(time.now_ns(), start)
 
deny if {
    hours > 1
}

Fungsi Agregasi

Fungsi untuk bekerja dengan koleksi nilai.

count

Hitung jumlah elemen dalam array, set, atau objek.

Contoh

# Limit number of contracts in a request
deny if {
    count(input.contract_addresses) > 5
}
 
# Ensure at least one address
deny if {
    count(input.contract_addresses) == 0
}

sum

Hitung jumlah angka dalam array.

Contoh

# Block if total gas across params exceeds limit
deny if {
    gas_values := [to_number(p.gas) | some p in input.raw_params; p.gas != null]
    sum(gas_values) > 5000000
}

max

Temukan nilai maksimum dalam array.

Contoh

# Check against maximum in a set of thresholds
thresholds := [1000, 5000, 10000]
 
deny if {
    input.usd_value > max(thresholds)
}

min

Temukan nilai minimum dalam array.

Contoh

# Ensure value meets minimum threshold
thresholds := [100, 500, 1000]
 
deny if {
    input.usd_value < min(thresholds)
}

sort

Urutkan array dalam urutan menaik.

Contoh

# Check if smallest contract address looks suspicious (many leading zeros)
deny if {
    count(input.contract_addresses) > 0
    sorted_addrs := sort(input.contract_addresses)
    startswith(sorted_addrs[0], "0x00000000")
}

product

Hitung hasil kali angka dalam array.

Contoh

# Calculate combined risk score from multiple factors
deny if {
    risk_factors := [2, 3]  # High-value = 2x, Unknown sender = 3x
    combined_risk := product(risk_factors)
    combined_risk > 5
}

Fungsi Tipe

Fungsi untuk memeriksa dan bekerja dengan tipe data. Berguna untuk menangani bidang nullable dengan aman.

is_null

Periksa apakah nilai adalah null. Penting untuk menangani bidang input opsional.

Contoh

# Safely check nullable field
deny if {
    not is_null(input.usd_value)
    input.usd_value > 10000
}

is_number

Periksa apakah nilai adalah angka.

Contoh

# Validate before numeric comparison
deny if {
    is_number(input.usd_value)
    input.usd_value > 10000
}

is_string

Periksa apakah nilai adalah string.

Contoh

# Validate input type
deny if {
    is_string(input.to_address)
    startswith(input.to_address, "0x0000")
}

is_array

Periksa apakah nilai adalah array.

Contoh

# Check before iterating
deny if {
    is_array(input.contract_addresses)
    count(input.contract_addresses) > 10
}

is_boolean

Periksa apakah nilai adalah boolean (true atau false).

Contoh

# Verify a flag is actually a boolean before using it
deny if {
    is_boolean(input.raw_params[0].enabled)
    input.raw_params[0].enabled == false
}

is_set

Periksa apakah nilai adalah set.

Contoh

# Validate collection type
deny if {
    is_set(input.raw_params[0].addresses)
    count(input.raw_params[0].addresses) > 100
}

is_object

Periksa apakah nilai adalah objek (peta kunci-nilai).

Contoh

# Ensure params is an object before accessing fields
deny if {
    is_object(input.raw_params[0])
    object.get(input.raw_params[0], "dangerous", false) == true
}

type_name

Dapatkan nama tipe nilai sebagai string.

Contoh

# Block if usd_value is not a number (unexpected type)
deny if {
    input.usd_value != null
    type_name(input.usd_value) != "number"
}

Fungsi Angka

Fungsi untuk operasi numerik.

abs

Dapatkan nilai absolut dari angka.

Contoh

# Check magnitude regardless of sign
deny if {
    abs(input.usd_value) > 10000
}

round

Bulatkan angka ke bilangan bulat terdekat.

Contoh

# Round for comparison
deny if {
    round(input.usd_value) > 10000
}

ceil

Bulatkan angka ke atas ke bilangan bulat berikutnya.

Contoh

# Round up for conservative limit checking
deny if {
    ceil(input.usd_value) > 10000
}

floor

Bulatkan angka ke bawah ke bilangan bulat sebelumnya.

Contoh

# Block transactions over $10,000 (ignoring cents)
deny if {
    floor(input.usd_value) >= 10000
}

to_number

Konversi string menjadi angka. Berguna untuk nilai string heksadesimal.

Contoh

# Convert hex gas values
deny if {
    input.gas_limit != null
    to_number(input.gas_limit) > 1000000
}

numbers.range

Hasilkan array angka dari awal hingga akhir (inklusif).

Contoh

# Allow transactions only during business hours (9 AM - 5 PM)
deny if {
    [hour, _, _] := time.clock(time.now_ns())
    business_hours := numbers.range(9, 17)
    not hour in business_hours
}

Fungsi Objek

Fungsi untuk bekerja dengan objek (peta kunci-nilai).

object.get

Dapatkan nilai dari objek dengan aman dengan default jika kunci tidak ada.

Contoh

# Safely access nested data
deny if {
    params := input.raw_params[0]
    data := object.get(params, "data", "0x")
    startswith(data, "0xa9059cbb")  # ERC-20 transfer
}

object.keys

Dapatkan semua kunci dari objek sebagai array.

Contoh

# Check which fields are present
params := input.raw_params[0]
keys := object.keys(params)
 
deny if {
    "data" in keys
    "value" in keys
}

object.remove

Buat objek baru dengan kunci yang ditentukan dihapus.

Contoh

# Block if params contain unexpected fields after removing known safe ones
deny if {
    safe_fields := ["to", "from", "value", "gas", "data"]
    remaining := object.remove(input.raw_params[0], safe_fields)
    count(object.keys(remaining)) > 0
}

object.union

Gabungkan dua objek. Nilai dari objek kedua menimpa yang pertama.

Contoh

# Apply safe defaults and check resulting gas limit
deny if {
    defaults := {"gas": "0x5208"}
    params := object.union(defaults, input.raw_params[0])
    to_number(params.gas) > 1000000
}

Fungsi Array

Fungsi untuk manipulasi array.

array.concat

Gabungkan dua array menjadi satu.

Contoh

# Combine address lists
all_addresses := array.concat(
    input.contract_addresses,
    [input.to_address]
)

array.slice

Ekstrak sebagian array berdasarkan indeks awal dan akhir.

Contoh

# Only check first 5 contract addresses for blocked list
deny if {
    first_five := array.slice(input.contract_addresses, 0, 5)
    some addr in first_five
    addr in {"0xbanned1...", "0xbanned2..."}
}

array.reverse

Balikkan urutan elemen dalam array.

Contoh

# Check last contract address (most recent) for suspicious patterns
deny if {
    count(input.contract_addresses) > 0
    reversed := array.reverse(input.contract_addresses)
    startswith(reversed[0], "0x00000000")
}

Fungsi Set

Fungsi untuk operasi set.

intersection

Dapatkan elemen yang ada di kedua set.

Contoh

# Check for any blocked address
blocked := {"0xdead...", "0xbad..."}
request_addrs := {lower(input.to_address)}
 
deny if {
    count(intersection(blocked, request_addrs)) > 0
}

union

Gabungkan dua set menjadi satu dengan semua elemen unik.

Contoh

# Combine multiple blocklists
blocked_countries := union(
    {"KP", "IR", "CU"},
    {"SY", "RU"}
)
 
deny if {
    input.source_country in blocked_countries
}

Fungsi Encoding

Fungsi untuk encoding dan decoding data.

base64.encode

Encode string ke format Base64.

Contoh

# Check if method matches an encoded pattern
deny if {
    encoded_method := base64.encode(input.rpc_method)
    encoded_method == "ZXRoX3NlbmRUcmFuc2FjdGlvbg=="  # eth_sendTransaction
}

base64.decode

Decode string Base64 kembali ke teks biasa.

Contoh

# Decode base64 data from request
decoded := base64.decode("aGVsbG8=")  # "hello"
 
deny if {
    contains(decoded, "dangerous")
}

base64url.encode

Encode string ke format Base64 yang aman untuk URL. Menggunakan - dan _ sebagai ganti + dan /.

Contoh

# Create URL-safe identifier from address for comparison
deny if {
    encoded_addr := base64url.encode(input.to_address)
    encoded_addr in {"MHhkZWFk...", "MHhiYWQ..."}
}

base64url.decode

Decode string Base64 yang aman untuk URL kembali ke teks biasa.

Contoh

# Decode and check URL-safe encoded data in params
deny if {
    encoded_data := object.get(input.raw_params[0], "encoded", "")
    decoded := base64url.decode(encoded_data)
    contains(decoded, "malicious")
}

hex.encode

Encode string ke format heksadesimal.

Contoh

# Encode method name to hex for pattern matching
deny if {
    method_hex := hex.encode(input.rpc_method)
    startswith(method_hex, "657468")  # "eth" in hex
}

hex.decode

Decode string heksadesimal kembali ke teks biasa.

Contoh

# Decode hex-encoded data field and check contents
deny if {
    data := object.get(input.raw_params[0], "data", "")
    startswith(data, "0x")
    decoded := hex.decode(substring(data, 2, 8))
    contains(decoded, "admin")
}
Fungsi Bawaan | 256 Blocks