General purpose functions
acquire-module-admin
Use acquire-module-admin
to grant module admin privileges for a particular module m
. You must already own admin for this particular module; that is, you must either be the owner of the keyset that grants the governance, or be able to pass the governance capability acquisition.
Basic syntax
Assume you have some module
(module my-module gov (defcap gov () (do-stuff-for-governance) ))
(module my-module gov (defcap gov () (do-stuff-for-governance) ))
To grant module admin, use
(acquire-module-admin some-module)
(acquire-module-admin some-module)
It will attempt to acquire the governance cap and if successful, it will grant module admin for the rest of the transaction.
Arguments
Use one of the following argument to define the value you want to retrieve using the at
Pact function.
Argument | Type | Description |
---|---|---|
ref | modref | Specifies the module to acquire administrative capabilities for. |
Return values
Module admin acquisition will either fail, or return "Module admin for module acquired"
Examples
See: Basic Syntax.
at
Use at
to retrieve the value at the location specified by an index
number or by a key
string in a collection.
If you specify an index
number, the collection must be a list of values.
If you specify a key
string, the collection must be an object.
Basic syntax
Because at
is an overloaded function, there are two ways to use it.
To get a value using the specified index
location from a list of values, use the following syntax:
(at index [list])
(at index [list])
To get a value using the specified key
string from an object, use the following syntax:
(at key {object})
(at key {object})
Arguments
Use one of the following argument to define the value you want to retrieve using the at
Pact function.
Argument | Type | Description |
---|---|---|
index | integer | Specifies the information you want to retrieve. If you specify an index number, the function returns the value from that location in a list of values. |
list | [integer or decimal] | Specifies the list of values to retrieve the value from using the specified index location. |
key | string | Specifies the information you want to retrieve. If you specify a key string, the function returns the value corresponding to that key from an object. |
object | object | Specifies the set of key and value pairs to retrieve the value from using the specified key . |
Return values
The at
function returns the value found at the specified index
or using the specified key
.
The return value can be any data type.
Examples
The following example returns the value found at the index
location—starting with 0—from a list of values.
For example, the value at index
location 3
is 14
:
(at 3 [20 18 16 14 12 10])14
(at 3 [20 18 16 14 12 10])14
You can use the at
function to return any type of data from a list.
For example:
(at 1 ["blue","green","red","yellow"])"green"
(at 1 ["blue","green","red","yellow"])"green"
The following example returns the value found at the specified key from an object:
(at "last-name" { "first-name": "maya", "last-name": "tea"})"tea"
(at "last-name" { "first-name": "maya", "last-name": "tea"})"tea"
You can use the at
function to return any type of data using the specified key from an object.
For example:
(at "chainId" { "networkId": "development", "chainId": 1, "auth": 0})1
(at "chainId" { "networkId": "development", "chainId": 1, "auth": 0})1
base64-decode
Use base64-decode
to convert a previously-encoded string
from unpadded base64 encoding to a string.
Basic syntax
To decode a string
from unpadded base64 encoding, use the following syntax:
(base64-decode string)
(base64-decode string)
Arguments
Use the following argument to specify the string
to decode using the base64-decode
Pact function.
Argument | Type | Description |
---|---|---|
string | string | Specifies the base64-encoded string to decode. |
Return values
The base64-decode
function returns the decoded string
.
Examples
The following example decodes a base64-encoded "aGVsbG8gd29ybGQh" string to the decoded "hello world!" string in the Pact REPL:
pact> (base64-decode "aGVsbG8gd29ybGQh")"hello world!"
pact> (base64-decode "aGVsbG8gd29ybGQh")"hello world!"
base64-encode
Use base64-encode
to convert the specified string
to an unpadded base64-encoded string.
Basic syntax
To encode a string
as unpadded base64, use the following syntax:
(base64-encode string)
(base64-encode string)
Arguments
Use the following argument to specify the string
to encode using the base64-encode
Pact function.
Argument | Type | Description |
---|---|---|
string | string | Specifies the string to encode as unpadded base64. |
Return values
The base64-encode
function returns the unpadded base64 encoded string
.
Examples
The following example converts the "hello world!" into the unpadded base64-encoded string "aGVsbG8gd29ybGQh" in the Pact REPL:
pact> (base64-encode "hello world!")"aGVsbG8gd29ybGQh"
pact> (base64-encode "hello world!")"aGVsbG8gd29ybGQh"
bind
Use bind
to evaluate a src
object, then apply the specified bindings
to bind field variables to values over subsequent body statements.
Basic syntax
To evaluate src
to an object and bind it with bindings
over subsequent body statements, use the following syntax:
(bind src bindings)
(bind src bindings)
Arguments
Use the following arguments to specify the src
object and bindings
for the bind
special form.
Argument | Type | Description |
---|---|---|
src | object:{row} | Specifies the source object to evaluate. |
bindings | binding:{row} | Specifies the bindings to apply to the src object. |
Return values
The bind
returns the result of evaluating the src
object with the specifies bindings
.
The data type depends on the data type of the field you specify for the bindings
argument.
Examples
The following example demonstrates the bind
special form in the Pact REPL:
pact> (bind { "a": 1, "b": 2 } { "a" := a-value } a-value)1
pact> (bind { "a": 1, "b": 2 } { "a" := a-value } a-value)1
In this example, bind
evaluates the object { "a": 1, "b": 2 }
and binds the value of "a" to a-value
. It then returns the value 1
, which is the value bound to a-value
.
chain-data
Use chain-data
to retrieve the blockchain-specific public metadata for a transaction.
This function returns an object with the following fields:
chain-id
: The chain identifier (0-19) for the blockchain where the transaction was executed.block-height
: The height of the block that includes the transaction.block-time
: The timestamp of the block that includes the transaction.prev-block-hash
: The hash of the previous block.sender
: The sender of the transaction.gas-limit
: The gas limit for the transaction.gas-price
: The gas price for the transaction.gas-fee
: The gas fee for the transaction.
Basic syntax
To retrieve the public metadata for a transaction using chain-data
, use the following syntax:
(chain-data)
(chain-data)
Arguments
You can use the chain-data
function without arguments in code that identifies the transaction that you want to return metadata for.
Return values
The chain-data
function returns the public metadata for a transaction as an object with the following fields
Field | Type | Description |
---|---|---|
chain-id | string | The chain identifier (0-19) for the blockchain where the transaction was executed. |
block-height | integer | The height of the block that includes the transaction. |
block-time | time | The timestamp of the block that includes the transaction. |
prev-block-hash | string | The hash of the previous block. |
sender | string | The sender of the transaction. |
gas-limit | integer | The gas limit for the transaction. |
gas-price | decimal | The gas price for the transaction. |
gas-fee | decimal | The gas fee for the transaction. |
Examples
If you call the chain-data
function in the Pact REPL without providing a transaction context in the surrounding code, the function returns the object with placeholder fields.
For example:
{"block-height": 0,"block-time": "1970-01-01T00:00:00Z","chain-id": "","gas-limit": 0,"gas-price": 0.0,"prev-block-hash": "","sender": ""}
{"block-height": 0,"block-time": "1970-01-01T00:00:00Z","chain-id": "","gas-limit": 0,"gas-price": 0.0,"prev-block-hash": "","sender": ""}
If you provide context for the call, the function returns an object with fields similar to the following:
pact> (chain-data){ "chain-id": "3", "block-height": 4357306, "block-time": "2024-06-06 20:12:56 UTC", "prev-block-hash": "33caae279bd584b655283b7d692d7e7b408d6549869c5eb6dcf2dc60021c3916", "sender": "k:1d5a5e10eb15355422ad66b6c12167bdbb23b1e1ef674ea032175d220b242ed4, "gas-limit": 2320, "gas-price": 1.9981e-7, "gas-fee": 726}
pact> (chain-data){ "chain-id": "3", "block-height": 4357306, "block-time": "2024-06-06 20:12:56 UTC", "prev-block-hash": "33caae279bd584b655283b7d692d7e7b408d6549869c5eb6dcf2dc60021c3916", "sender": "k:1d5a5e10eb15355422ad66b6c12167bdbb23b1e1ef674ea032175d220b242ed4, "gas-limit": 2320, "gas-price": 1.9981e-7, "gas-fee": 726}
In most cases, you use chain-data
in Pact modules or in combination with frontend libraries to return information in the context of a specific transaction.
The following example illustrates using chain-data in a Pact module to get the block time from a transaction:
(let ((curr-time:time (at 'block-time (chain-data))))
(let ((curr-time:time (at 'block-time (chain-data))))
CHARSET_ASCII
CHARSET_ASCII
is a constant used to indicate the standard ASCII character set.
Constant value
(CHARSET_ASCII:integer = 0)
Description
The CHARSET_ASCII
constant represents the ASCII (American Standard Code for Information Interchange) character set, which is a widely used character encoding that includes 128 characters. It consists of control characters, digits, lowercase and uppercase English letters, and various symbols.
When working with functions or modules that require specifying a character set, you can use CHARSET_ASCII
to indicate that the ASCII character set should be used.
CHARSET_LATIN1
CHARSET_LATIN1
is a constant used to indicate the standard Latin-1 (ISO-8859-1) character set.
Constant value
(CHARSET_LATIN1:integer = 1)
Description
The CHARSET_LATIN1
constant represents the Latin-1 (ISO-8859-1) character set, which is a widely used single-byte character encoding. It includes characters from various Western European languages.
When working with functions or modules that require specifying a character set, you can use CHARSET_LATIN1
to indicate that the Latin-1 character set should be used.
compose
Use compose
to compose functions where oper1
performs an operation using the specified value
and oper2
takes the results from oper1
as input to produce the result for the composed function.
You can use any data type for the value
argument as long as the first oper1
functions can take that same data type.
By convention, the data type <a>
is used to represent a type-bound parameter like the value
argument in this function.
Basic syntax
To compose a function using oper1
and oper2
with the specified value
, use the following syntax:
(compose oper1 oper2 value)
(compose oper1 oper2 value)
Arguments
Use the following arguments to specify the functions oper1
and oper2
for composing with value
using the compose
Pact function.
Argument | Type | Description |
---|---|---|
oper1 | function: <a> -> <b> | Specifies the first function to operate on the specified value and return a result to provide input to the second function. |
oper2 | function: <b> -> <c> | Specifies the second function to operate on the results of the oper1 function. |
value | <a> | Specifies the value on which oper1 operates. |
Return values
The compose
function returns the result of applying oper2
to the result returned by oper1
for the specified value
.
Examples
In the following example, compose
uses the contains
function to evaluate the specified list for a string, then uses the if
function to operate on the results of the contains
function to display the final result:
pact> (compose (contains "summer") (if true "Success!") ["spring" "summer" "fall" "winter"]) "Success!"
pact> (compose (contains "summer") (if true "Success!") ["spring" "summer" "fall" "winter"]) "Success!"
concat
Use concat
to take a list of strings str-list
and concatenate each of the strings in the list, returning the resulting string.
Basic syntax
To concatenate each string in a list, use the following syntax:
(concat [str-list])
(concat [str-list])
Arguments
Use the following argument to specify the list of strings str-list
for the concat
Pact function.
Argument | Type | Description |
---|---|---|
str-list | [string] | Specifies the list of strings to concatenate. |
Return values
The concat
function returns the resulting string after concatenating all the strings in the str-list
.
Examples
The following example demonstrates the concat
function in the Pact REPL:
pact>(concat ["k" "d" "a"])"kda"
pact>(concat ["k" "d" "a"])"kda"
In this example, concat
takes the list ["k" "d" "a"]
and concatenates each string in the list, resulting in the string "kda"
.
The following example shows how to concatenate a list of strings after mapping each element with a function:
pact>(concat (map (+ " ") (str-to-list "abcde")))"a b c d e"
pact>(concat (map (+ " ") (str-to-list "abcde")))"a b c d e"
In this example, (str-to-list "abcde")
converts the string "abcde"
into a list of characters ["a" "b" "c" "d" "e"]
. Then, (map (+ " ") ...)
maps the function (+ " ")
to each character, adding a space after each character. Finally, concat
concatenates all the strings in the resulting list, producing the string "a b c d e"
.
constantly
Use constantly
to lazily ignore the specified ignore
arguments and return the specified vale
.
Basic syntax
To lazily ignore arguments and return a value, use the following syntax:
(constantly value ignore1 ignore2 ...)
(constantly value ignore1 ignore2 ...)
Arguments
Use the following arguments to specify the value
to return and the ignore
arguments for the constantly
Pact function.
Argument | Type | Description |
---|---|---|
value | any | Specifies the value to return. |
ignore1, ignore2, ... | any | Specifies the arguments to ignore. You can have multiple ignore arguments (optional). |
Return values
The constantly
function returns the specified value
, ignoring any additional arguments.
Examples
The following example demonstrates the constantly
function in the Pact REPL:
pact> (filter (constantly true) [1 2 3])[1 2 3]
pact> (filter (constantly true) [1 2 3])[1 2 3]
In this example, constantly true
is used as the predicate function for the filter
function.
The constantly
function always returns true
and ignores the elements of the [1 2 3]
list argument, so the filter
function always returns the entire list.
The following example illustrate specifying multiple arguments and argument using different data types:
pact> (constantly "hello" {"name": "Kris", "age": 45})"hello" pact> (constantly "world" 6 "ignore" "these" "arguments" [2.1 3.0])"world" pact> (constantly 42 "ignore" 123 "arguments")42
pact> (constantly "hello" {"name": "Kris", "age": 45})"hello" pact> (constantly "world" 6 "ignore" "these" "arguments" [2.1 3.0])"world" pact> (constantly 42 "ignore" 123 "arguments")42
contains
Use contains
to test whether a list
contains a value
, an object
has a key
entry, or a string
contains a substring value
.
Basic syntax
Because contains
is an overloaded function, there are a few different ways to use it.
To test whether a list
contains a value
, use the following syntax:
(contains value [list])
(contains value [list])
To test whether an object
has a key
entry, use the following syntax:
(contains key {object})
(contains key {object})
To test whether a string
contains a substring value
, use the following syntax:
(contains value string)
(contains value string)
Arguments
Use the following arguments to specify the value
, list
, key
, object
, string
for the contains
Pact function.
Argument | Type | Description |
---|---|---|
value | any | Specifies the value to search for in a list or string . |
list | [any] | Specifies the list to search for the specified value . |
key | any | Specifies the key to check for in an object . |
object | object | Specifies the object to check for the specified key . |
string | string | Specifies the string to search for the specified value . |
Return values
The contains
function returns a boolean value indicating whether the specified value
or the specified key
was found.
Examples
The following examples demonstrate the contains
function in the Pact REPL.
To check whether a list
contains a specified value
:
pact> (contains 2 [1 2 3])true
pact> (contains 2 [1 2 3])true
In this example, the contains
functions checks whether the value 2
is included in the [1 2 3]
list. Because the list contains the specified value, the contains
function returns true
.
To check whether a specified object
has 'name
as a key field:
pact> (contains 'name { 'name: "Ted", 'age: 72 })true
pact> (contains 'name { 'name: "Ted", 'age: 72 })true
To check whether the string "foobar"
contains the substring "foo"
,
pact> (contains "foo" "foobar")true
pact> (contains "foo" "foobar")true
In this example, contains "foo" "foobar"
checks which it does, so it returns true
.
continue
Use continue
to continue a previously-started multi-step transaction.
Transactions that have multiple steps executed in a sequence are called pacts and are defined using the defpact
keyword.
Steps can be nested in defpact
structures and the continue
function enables you to continue execution with a specified value.
Basic syntax
To continue a previously-started defpact
transaction, use the following syntax:
(continue value)
(continue value)
Arguments
Use the following argument to specify the value
to continue the nested defpact
.
Argument | Type | Description |
---|---|---|
value | any | Specifies the value to continue the nested defpact . |
Return values
The continue
function continues the execution of the nested defpact
with the specified value
.
Examples
The following example demonstrates the use of continue
within the context of a defpact
to resume its execution with a specified value.
(defpact transfer-crosschain:string ( sender:string receiver:string receiver-guard:guard target-chain:string amount:decimal ) (step (with-capability (TRANSFER_XCHAIN sender receiver amount target-chain) (install-capability (coin.TRANSFER sender receiver amount)) (coin.transfer-crosschain sender receiver receiver-guard target-chain amount) ) ) (step (continue (coin.transfer-crosschain sender receiver receiver-guard target-chain amount)) ) )
(defpact transfer-crosschain:string ( sender:string receiver:string receiver-guard:guard target-chain:string amount:decimal ) (step (with-capability (TRANSFER_XCHAIN sender receiver amount target-chain) (install-capability (coin.TRANSFER sender receiver amount)) (coin.transfer-crosschain sender receiver receiver-guard target-chain amount) ) ) (step (continue (coin.transfer-crosschain sender receiver receiver-guard target-chain amount)) ) )
define-namespace
Use define-namespace
to create a new namespace or update the guards of an existing namespace. The ownership and use of the namespace are controlled by the specified guards.
Note: This function can only be used at the top level of your code. It will fail if used within module code.
Basic syntax
To define the namespace namespace
, use the following syntax:
(define-namespace namespace user-guard admin-guard)
(define-namespace namespace user-guard admin-guard)
Arguments
Use the following arguments to specify the namespace and guards when using the define-namespace
Pact function.
Argument | Type | Description |
---|---|---|
namespace | string | Specifies the name of the namespace to create or update. |
user-guard | guard | Specifies the guard that controls who can use the namespace. |
admin-guard | guard | Specifies the guard that controls the ownership and administrative tasks in the namespace. |
Return value
The define-namespace
function returns the name of the created or updated namespace as a string.
Example
The following example creates a new namespace called 'my-namespace'
with user and admin guards defined by the 'user-ks'
and 'admin-ks'
keysets, respectively:
(define-namespace 'my-namespace (read-keyset 'user-ks) (read-keyset 'admin-ks))
(define-namespace 'my-namespace (read-keyset 'user-ks) (read-keyset 'admin-ks))
describe-namespace
Use describe-namespace
to describe the specified namespace
, returning a row object containing the user and admin guards of the namespace, as well as its name.
Basic syntax
To describe the namespace namespace
, use the following syntax:
(describe-namespace namespace)
(describe-namespace namespace)
Prerequisites
You must define a namespace with the define-namespace function before you can use the describe-namespace
function.
For information about defining a namespace, see define-namespace.
Arguments
Use the following argument to specify the namespace
for the describe-namespace
Pact function.
Argument | Type | Description |
---|---|---|
namespace | string | Specifies the name of the namespace to describe. |
Return values
The describe-namespace
function returns an object with detailed information about the specified namespace
.
Examples
The following example demonstrates the describe-namespace
function:
pact> (env-data { "keyset": ["fake-key"]})"Setting transaction data"pact> (define-namespace 'my-namespace (read-keyset 'keyset) (read-keyset 'keyset))"Namespace defined: my-namespace"pact> (describe-namespace 'my-namespace)"admin-guard":KeySet {keys: [fake-key],pred: keys-all}, "namespace-name":"my-namespace", "user-guard":KeySet {keys: [ fake-key ],pred: keys-all}}
pact> (env-data { "keyset": ["fake-key"]})"Setting transaction data"pact> (define-namespace 'my-namespace (read-keyset 'keyset) (read-keyset 'keyset))"Namespace defined: my-namespace"pact> (describe-namespace 'my-namespace)"admin-guard":KeySet {keys: [fake-key],pred: keys-all}, "namespace-name":"my-namespace", "user-guard":KeySet {keys: [ fake-key ],pred: keys-all}}
In this example, (describe-namespace 'my-namespace)
is used to describe the namespace named 'my-namespace'. The function returns a row object containing the user and admin guards of the namespace, as well as its name. This provides a detailed description of the specified namespace.
distinct
Use distinct
to return a list with duplicates removed from a homogeneous list of values
.
The original order of the values is preserved.
Basic syntax
To return a list with duplicates removed from a list of values
, use the following syntax:
(distinct [values])
(distinct [values])
Arguments
Use the following argument to specify the list of VALUES
for the distinct
Pact function.
Argument | Type | Description |
---|---|---|
values | [any] | Specifies the list of values that includes duplicates. |
Return values
The distinct
function returns a list with duplicates removed from the specified list of values
.
Examples
The following example demonstrates how to use the distinct
function to remove duplicates from a list of numeric values:
pact>(distinct [3 3 1 1 2 2])[3, 1, 2]
pact>(distinct [3 3 1 1 2 2])[3, 1, 2]
The function returns [3 1 2]
, preserving the original order of the values.
drop
Use drop
to remove a specified number of values from a list, string, or object.
Basic syntax
Because drop
is an overloaded function, there are two ways to use it.
To remove the specified count
number of values from a list
or string, use the following syntax:
(drop count [list])
(drop count [list])
To remove the specified keys
and corresponding values from an object
or string, use the following syntax:
(drop keys {object})
(drop keys {object})
Arguments
Use the following arguments to specify the count
and list
or keys
and object
for the drop
Pact function:
Argument | Type | Description |
---|---|---|
count | integer | Specifies the number of values to drop from the list or a string. |
list | [any] or string | Specifies the list (or string) from which to drop values. |
keys | [string] | Specifies the keys to drop from the object. |
object | object | Specifies the object from which to drop entries with specified keys. |
Return values
The drop
function returns the modified list, string, or object after removing the specified number of values or specified keys.
Examples
The following example demonstrates how to use the drop
function to drop the first two characters from the specified string:
pact> (drop 2 "vwxyz")"xyz"
pact> (drop 2 "vwxyz")"xyz"
The following example illustrates how to drop the last two values from the specified list:
pact> (drop -2 [1 2 3 4 5])[1, 2, 3]
pact> (drop -2 [1 2 3 4 5])[1, 2, 3]
The following example drops the key 'name
and its corresponding value from the specified object:
pact> (drop ['name] { 'name: "Vlad", 'active: false }){'active: false}
pact> (drop ['name] { 'name: "Vlad", 'active: false }){'active: false}
enforce-guard
Use enforce-guard
to execute a specified guard
or a defined keyset named keysetname
to enforce the predicate logic.
Basic syntax
To use a guard
to enforce specific conditions defined in predicate logic, use the following syntax:
(enforce-guard guard)
(enforce-guard guard)
To use a defined keyset as a guard
to enforce specific conditions defined in predicate logic, use the following syntax:
(enforce-guard keysetname)
(enforce-guard keysetname)
Arguments
Use the following arguments to specify the guard
or keysetname
for the enforce-guard
Pact function:
Argument | Type | Description |
---|---|---|
guard | guard | Specifies the name of the guard to execute. |
keysetname | string | Specifies the name of the defined keyset to enforce. |
Return values
The enforce-guard
function returns a boolean value indicating whether the conditions specified in the predicate logic that the guard or keyset is there to enforce were met.
Examples
The following example demonstrates using the keyset guard named admin-keyset
to enforce specific signing requirements defined in the keyset predicate function, for example with the keys-all
or keys-2
predicate:
(enforce-guard 'admin-keyset)
(enforce-guard 'admin-keyset)
In most cases, you use enforce-guard
in the context of contract logic to ensure a specific condition is true
before allowing a specific operation to be executed.
For example, you might have logic to validate a sender account before allowing a transfer operation.
You can then call the enforce-guard
to ensure the sender meets the specified conditions—returning true
as a result—before executing further logic:
(enforce-guard sender-guard)
(enforce-guard sender-guard)
enforce-one
Use enforce-one
to run a series of tests in order (in a pure context, plus keyset enforces).
If all tests fail, the transaction fails. This function short-circuits on the first successful test.
Basic syntax
To run a series of tests in order and short-circuit on the first successful test, use the following syntax:
(enforce-one msg tests)
(enforce-one msg tests)
Arguments
Use the following arguments to specify the error message and tests for the enforce-one
Pact function:
Argument | Type | Description |
---|---|---|
msg | string | Specifies the error message if all tests fail. |
tests | bool | Specifies the list of tests to run in order. |
Return values
The enforce-one
function returns true
if at least one test succeeds.
If all tests fail, the function fails the transaction with the specified error message.
Examples
The following example demonstrates the enforce-one
function:
pact> (enforce-one "Should succeed on second test" [(enforce false "Skip me") (enforce (= (+ 2 2) 4) "Chaos reigns")])true
pact> (enforce-one "Should succeed on second test" [(enforce false "Skip me") (enforce (= (+ 2 2) 4) "Chaos reigns")])true
In this example, (enforce-one "Should succeed on second test" [(enforce false "Skip me") (enforce (= (+ 2 2) 4) "Chaos reigns")])
is used to run two tests in order.
The first test is enforce false "Skip me"
, which fails intentionally.
The second test is (enforce (= (+ 2 2) 4) "Chaos reigns")
, which succeeds because 4 = 4
is true.
Because the second test succeeds, the enforce-one
function returns true
.
If all tests had failed, the transaction would have failed with the specified error message "Should succeed on second test".
enforce-pact-version
Use enforce-pact-version
to enforce the runtime Pact version to be within a specified range, where the version is greater than or equal to the min-version
argument and less than or equal to the max-version
argument.
The max-version
argument is optional.
Version values are matched numerically from the left, meaning versions like '2', '2.2', and '2.2.3' would all allow '2.2.3'.
Basic syntax
To enforce the runtime Pact version within a specified range, use the following syntax:
(enforce-pact-version min-version max-version)
(enforce-pact-version min-version max-version)
Arguments
Use the following arguments to specify the minimum and maximum Pact versions for the enforce-pact-version
Pact function:
Argument | Type | Description |
---|---|---|
min-version | string | Specifies the minimum Pact version to enforce. |
max-version | string | Specifies the maximum Pact version to enforce (optional). |
Return values
The enforce-pact-version
function returns a boolean value indicating whether the runtime Pact version is within the specified range.
Examples
The following example demonstrates how to use the enforce-pact-version
function to ensure that the runtime Pact version is at least "4.10":
pact>(enforce-pact-version "4.10")true
pact>(enforce-pact-version "4.10")true
If the current Pact version is "4.10" or higher, the function returns true
.
If the Pact version is lower than "4.10" or you specify an invalid version, the function fails.
<interactive>:0:0:Error: Invalid pact version 4.10, minimum allowed: 4.4
<interactive>:0:0:Error: Invalid pact version 4.10, minimum allowed: 4.4
You can also specify a maximum Pact version:
pact>(enforce-pact-version "4.0" "4.10")true
pact>(enforce-pact-version "4.0" "4.10")true
enforce-verifier
Use enforce-verifier
to enforce that a verifier plugin with the specified verifier-name
is in scope.
Basic syntax
To enforce that a verifier is in scope, use the following syntax:
(enforce-verifier verifier-name)
(enforce-verifier verifier-name)
Arguments
Use the following argument to specify the verifier-name
for the enforce-verifier
Pact function:
Argument | Type | Description |
---|---|---|
verifier-name | string | Specifies the name of the verifier to enforce. |
Return values
The enforce-verifier
function returns a boolean value indicating whether the specified verifier is in scope.
Examples
The following example demonstrates the enforce-verifier
function:
pact> (enforce-verifier 'COOLZK)<interactive>:0:0:Error: Verifier failure COOLZK: not in transaction
pact> (enforce-verifier 'COOLZK)<interactive>:0:0:Error: Verifier failure COOLZK: not in transaction
In this example, (enforce-verifier 'COOLZK)
is used to enforce that the verifier named 'COOLZK' is in scope.
If the verifier 'COOLZK' is in scope, the function returns true
.
If the verifier is not in scope, the function fails.
The enforce-verifier
function provides a way to ensure that a specific verifier is available for use within a Pact contract.
enforce
Use enforce
to test whether a pure expression
evaluates to true or false.
If the specified expression
evaluates to true, the function returns true.
If the specified expression
evaluates to false, the function fails the transaction and displays the specified error message
.
Basic syntax
To fail a transaction with a specified error message if an expression evaluates to false, use the following syntax:
(enforce expression message)
(enforce expression message)
Arguments
Use the following arguments to specify the test expression and error message for the enforce
Pact function:
Argument | Type | Description |
---|---|---|
expression | bool | Specifies the expression to evaluate. |
message | string | Specifies the error message to display if the expression evaluates as false. |
Return values
The enforce
function returns true
if the specified expression
is true. If the expression
is false, the function fails the transaction with the specified error message.
Examples
The following example demonstrates how to use the enforce
function to evaluate the expression (+ 2 2) != 4
:
pact> (enforce (= (+ 2 2) 4) "All is well")true
pact> (enforce (= (+ 2 2) 4) "All is well")true
Because the specified expression (4 = 4
) is true, the function returns true and the transaction continues.
If the expression were false, the transaction would fail with the error message "Chaos reigns". The enforce
function provides a way to ensure conditions are met within a transaction.
enumerate
Use enumerate
to return a sequence of numbers from the specified first
number to the specified last
number, inclusively, as a list.
By default, the sequence increments by one from the first
number to the last
number.
Optionally, you can specify an increment other than one to use between numbers in the sequence.
If you specify a first
number that’s greater than the last
number, the sequence decrements by one from the first
number to the last
number.
Basic syntax
To increment or decrement the sequence by one, use the following syntax:
(enumerate first last)
(enumerate first last)
To specify a value to increment or decrement the sequence by, use the following syntax:
(enumerate first last inc)
(enumerate first last inc)
Arguments
Use the following arguments to define the beginning and end of the sequence you want to list using the enumerate
Pact function.
Argument | Type | Description |
---|---|---|
first | integer | Specifies the first number in the sequence. |
last | integer | Specifies the last number in the sequence. |
Options
Use the following option to define the increment to use between the beginning and end of the sequence in the enumerate
Pact function.
Option | Type | Description |
---|---|---|
inc | integer | Specifies the increment to use between numbers in the sequence. The value can be a positive or negative integer. |
Return values
The enumerate
function returns the resulting sequence of numbers as a list.
Examples
The following example enumerates a sequence of numbers using the default increment of one in the Pact REPL:
pact>(enumerate 0 10)[0 1 2 3 4 5 6 7 8 9 10]
pact>(enumerate 0 10)[0 1 2 3 4 5 6 7 8 9 10]
The following example enumerates a sequence of numbers using an increment of two between numbers in the sequence:
pact>(enumerate 0 10 2)[0 2 4 6 8 10]
pact>(enumerate 0 10 2)[0 2 4 6 8 10]
The following example illustrates decrementing a sequence of numbers using an inc
value of -2 between numbers in the sequence:
(enumerate 20 10 -2)[20 18 16 14 12 10]
(enumerate 20 10 -2)[20 18 16 14 12 10]
filter
Use filter
to filter a list of elements
by applying the specified apply
function to each element in the list.
For each element in the list, the apply
function should return true or flase to identify the elements that should be included in the filtered list.
Each element that returns a result of true
from the apply
function is included in the resulting list with its original value.
With the filter
function, you can include elements in a list based on a specific condition.
Basic syntax
To filter a list by applying a function to each element, use the following syntax:
(filter apply [elements])
(filter apply [elements])
Arguments
Use the following arguments to specify the function and list for the filter
Pact function:
Argument | Type | Description |
---|---|---|
apply | function | Specifies the function to apply to each element of the list. The return value for the function must be a Boolean (true or false ) to identify elements to be included in the resulting list. |
elements | [any] | Specifies the list of elements to filter. The elements in the list can be any data type. |
Return values
The filter
function returns a new list containing elements from the original list for which the apply
function returns true
.
Examples
The following example demonstrates how to use filter
with a function that evaluates the length of strings to only include the strings with more than two characters:
(filter (lambda (str) (< 2 (length str))) ["my" "dog" "has" "fleas"])["dog" "has" "fleas"]
(filter (lambda (str) (< 2 (length str))) ["my" "dog" "has" "fleas"])["dog" "has" "fleas"]
In this example, (lambda (str) (< 2 (length str)))
is used as the function that is applied to each element.
This function checks the length of each element in the list.
The filter
function then filters the list ["my" "dog" "has" "fleas"]
based on this condition.
The resulting list only contains the elements that returned true
when the function was applied. In this case, the resulting list is ["dog" "has" "fleas"]
.
In the following example, (compose (length) (= 3))
is the function applied to each element:
pact> (filter (compose (length) (= 3)) ["my" "red" "dog" "has" "fleas"])["red" "dog" "has"]
pact> (filter (compose (length) (= 3)) ["my" "red" "dog" "has" "fleas"])["red" "dog" "has"]
Like the previous example, the (compose (length) (= 3))
function checks the length of each element in the list.
The filter
function then filters the list based on this condition and the resulting list only contains the elements that returned true
when the function was applied.
In this case, the resulting list is ["red" "dog" "has"]
.
fold
Use fold
to iteratively reduce a list by applying the app
function to the last result for each element in the list, starting with the specified init
initial value.
You can use any data type for the value
argument as long as the first oper1
functions can take that same data type.
By convention, data type notation like <a>
and <b>
are used to represent type-bound parameters like the init
and list
arguments in this function.
Basic syntax
To iteratively reduce a list by applying a function to each element, starting with an initial value, use the following syntax:
(fold app init [list])
(fold app init [list])
Arguments
Use the following arguments to specify the function, initial value, and list for the fold
Pact function:
Argument | Type | Description |
---|---|---|
app | function x: <a> y: <b> -> <a> | Specifies the function to apply to each element and the last result. |
init | <a> | Specifies the initial value for the reduction. |
list | [<b> ] | Specifies the list to iterate over. |
Return values
The fold
function returns the final result of the iterative reduction of the list.
Examples
The following example demonstrates the fold
function:
pact>(fold (+) 0 [100 10 5])115
pact>(fold (+) 0 [100 10 5])115
In this example, (+)
is used as the function to apply, which is addition in this case.
The fold
function starts with an initial value of 0
and iteratively adds each element of the list [100 10 5]
to the previous result. Here's the breakdown:
- Initial value:
0
- First iteration:
0 + 100 = 100
- Second iteration:
100 + 10 = 110
- Third iteration:
110 + 5 = 115
The final result of the fold
operation is 115
. The fold
function is commonly used for operations that require accumulating results over a list in Pact contracts.
format
Use format
to input specified variables
into a template
string in the location specified using curly braces ({}
) as template placeholders.
Basic syntax
To input variables into a template string where specified by the {}
placeholders, use the following syntax:
(format template variables)
(format template variables)
Arguments
Use the following arguments to specify the template string and variables for the format
Pact function:
Argument | Type | Description |
---|---|---|
template | string | Specifies the template string with {} placeholders. |
variables | [any] | Specifies the variables to insert into the template placeholders. |
Return values
The format
function returns a new string with the values from the specified variables replacing the placeholder curly braces {}
from the template string.
Examples
The following example demonstrates how to use the format
function with "My {} has {}"
as the template string with two {}
placeholders:
pact> (format "My {} has {}" ["dog" "fleas"])"My dog has fleas"
pact> (format "My {} has {}" ["dog" "fleas"])"My dog has fleas"
In this example, the format
function replaces the placeholders in the template string with the specified values ["dog", "fleas"]
to return the result "My dog has fleas"
.
The format
function is often used to create dynamic strings with variables inserted into specific locations in Pact contracts.
For example, you can use the variables to store dynamic values like the current time:
(enforce (>= curr-time release-time) (format "Funds locked until {}. Current time: {}" [release-time curr-time]))
(enforce (>= curr-time release-time) (format "Funds locked until {}. Current time: {}" [release-time curr-time]))
hash-keccak256
Use hash-keccak256
to compute the hash of a list of unpadded base64url-encoded inputs VALUES
.
The hash is computed incrementally over all of the decoded inputs.
Basic syntax
To compute the hash of a list of inputs, use the following syntax:
(hash-keccak256 VALUES)
Arguments
Use the following argument to specify the list of inputs for the hash-keccak256
Pact function:
Argument | Type | Description |
---|---|---|
VALUES | [string] | Specifies the list of unpadded base64url-encoded inputs. |
Return values
The hash-keccak256
function returns a string representing the computed hash value.
Examples
The following examples demonstrate the hash-keccak256
function:
pact>(hash-keccak256 [])"xdJGAYb3IzySfn2y3McDwOUAtlPKgic7e_rYBF2FpHA"
pact>(hash-keccak256 [])"xdJGAYb3IzySfn2y3McDwOUAtlPKgic7e_rYBF2FpHA"
In this example, an empty list []
is provided as input. The hash-keccak256
function computes the hash of the empty list and returns the hash value.
(hash-keccak256 ["T73FllCNJKKgAQ4UCYC4CfucbVXsdRJYkd2YXTdmW9gPm-tqUCB1iKvzzu6Md82KWtSKngqgdO04hzg2JJbS-yyHVDuzNJ6mSZfOPntCTqktEi9X27CFWoAwWEN_4Ir7DItecXm5BEu_TYGnFjsxOeMIiLU2sPlX7_macWL0ylqnVqSpgt-tvzHvJVCDxLXGwbmaEH19Ov_9uJFHwsxMmiZD9Hjl4tOTrqN7THy0tel9rc8WtrUKrg87VJ7OR3Rtts5vZ91EBs1OdVldUQPRP536eTcpJNMo-N0fy-taji6L9Mdt4I4_xGqgIfmJxJMpx6ysWmiFVte8vLKl1L5p0yhOnEDsSDjuhZISDOIKC2NeytqoT9VpBQn1T3fjWkF8WEZIvJg5uXTge_qwA46QKV0LE5AlMKgw0cK91T8fnJ-u1Dyk7tCo3XYbx-292iiih8YM1Cr1-cdY5cclAjHAmlglY2ia_GXit5p6K2ggBmd1LpEBdG8DGE4jmeTtiDXLjprpDilq8iCuI0JZ_gvQvMYPekpf8_cMXtTenIxRmhDpYvZzyCxek1F4aoo7_VcAMYV71Mh_T8ox7U1Q4U8hB9oCy1BYcAt06iQai0HXhGFljxsrkL_YSkwsnWVDhhqzxWRRdX3PubpgMzSI290C1gG0Gq4xfKdHTrbm3Q"])
(hash-keccak256 ["T73FllCNJKKgAQ4UCYC4CfucbVXsdRJYkd2YXTdmW9gPm-tqUCB1iKvzzu6Md82KWtSKngqgdO04hzg2JJbS-yyHVDuzNJ6mSZfOPntCTqktEi9X27CFWoAwWEN_4Ir7DItecXm5BEu_TYGnFjsxOeMIiLU2sPlX7_macWL0ylqnVqSpgt-tvzHvJVCDxLXGwbmaEH19Ov_9uJFHwsxMmiZD9Hjl4tOTrqN7THy0tel9rc8WtrUKrg87VJ7OR3Rtts5vZ91EBs1OdVldUQPRP536eTcpJNMo-N0fy-taji6L9Mdt4I4_xGqgIfmJxJMpx6ysWmiFVte8vLKl1L5p0yhOnEDsSDjuhZISDOIKC2NeytqoT9VpBQn1T3fjWkF8WEZIvJg5uXTge_qwA46QKV0LE5AlMKgw0cK91T8fnJ-u1Dyk7tCo3XYbx-292iiih8YM1Cr1-cdY5cclAjHAmlglY2ia_GXit5p6K2ggBmd1LpEBdG8DGE4jmeTtiDXLjprpDilq8iCuI0JZ_gvQvMYPekpf8_cMXtTenIxRmhDpYvZzyCxek1F4aoo7_VcAMYV71Mh_T8ox7U1Q4U8hB9oCy1BYcAt06iQai0HXhGFljxsrkL_YSkwsnWVDhhqzxWRRdX3PubpgMzSI290C1gG0Gq4xfKdHTrbm3Q"])
In this example, a list containing multiple base64url-encoded strings is provided as input. The hash-keccak256
function computes the hash of all the inputs and returns the hash value.
The hash-keccak256
function is useful for computing hash values of data for various cryptographic operations in Pact contracts.
hash
Use hash
to compute the BLAKE2b 256-bit hash of a specified value
. The resulting hash value is a Base64Url-encoded string without padding.
Strings values are converted directly.
Other data type values are converted using their JSON representation. Non-value-level arguments are not allowed.
By convention, the data type <a>
is used to represent a type-bound parameter like the value
argument in this function.
Basic syntax
To compute the BLAKE2b 256-bit hash of a value, use the following syntax:
(hash value)
(hash value)
Arguments
Use the following argument to specify the value for the hash
Pact function:
Argument | Type | Description |
---|---|---|
value | <a> | Specifies the value to be hashed. |
Return values
The hash
function returns a string representing the computed hash value.
Examples
The following example demonstrates how to use the hash
function to compute a hash for the "hello"
string value:
pact> (hash "hello")"Mk3PAn3UowqTLEQfNlol6GsXPe-kuOWJSCU0cbgbcs8"
pact> (hash "hello")"Mk3PAn3UowqTLEQfNlol6GsXPe-kuOWJSCU0cbgbcs8"
Because "hello"
is a string value, the hash
function computes the BLAKE2b 256-bit hash of the string "hello" and returns the hash value.
(hash { 'foo: 1 })"h9BZgylRf_M4HxcBXr15IcSXXXSz74ZC2IAViGle_z4"
(hash { 'foo: 1 })"h9BZgylRf_M4HxcBXr15IcSXXXSz74ZC2IAViGle_z4"
In this example, { 'foo: 1 }
is a JSON object. The hash
function computes the BLAKE2b 256-bit hash of the JSON representation of the object and returns the hash value.
The hash
function is useful for generating hash values of data for various cryptographic operations in Pact contracts.
identity
Use identity
to return the provided value.
Basic syntax
To return the provided value, use the following syntax:
(identity value)
Arguments
Use the following argument to specify the value you want to return using the identity
Pact function.
Argument | Type | Description |
---|---|---|
value | any | Specifies the value to be returned. |
Return value
The identity
function returns the provided value.
Examples
The following example demonstrates the use of identity
within a map
function in the Pact REPL:
pact>(map (identity) [1 2 3])[1 2 3]
pact>(map (identity) [1 2 3])[1 2 3]
This example applies the identity
function to each element in the list [1, 2, 3]
, effectively returning the same list.
if
Use if
to test a condition. If the condition cond
is true, evaluate the then
expression; otherwise, evaluate the else
expression.
By convention, the data type <a>
is used to represent type-bound parameters that serve as input for functions and expressions or for generic arguments.
Basic syntax
To test a condition and execute different expressions based on the result, use the following syntax:
(if cond then else)
(if cond then else)
Arguments
Use the following arguments to define the condition and expressions to be evaluated based on the outcome of the condition using the if
Pact function.
Argument | Type | Description |
---|---|---|
cond | boolean | Specifies the condition to be tested. |
then | <a> | Specifies the expression to be evaluated if the condition is true. |
else | <a> | Specifies the expression to be evaluated if the condition is false. |
Return value
The if
function returns the result of evaluating either the then
expression or the else
expression, depending on the outcome of the condition.
Examples
The following example demonstrates the use of if
to test a condition in the Pact REPL:
pact>(if (= (+ 2 2) 4) "Sanity prevails" "Chaos reigns")"Sanity prevails"
pact>(if (= (+ 2 2) 4) "Sanity prevails" "Chaos reigns")"Sanity prevails"
In this example, the condition (= (+ 2 2) 4)
evaluates to true, so the expression "Sanity prevails"
is returned.
pact>(if (= (+ 2 2) 5) "Sanity prevails" "Chaos reigns")"Chaos reigns"
pact>(if (= (+ 2 2) 5) "Sanity prevails" "Chaos reigns")"Chaos reigns"
In this example, the condition (= (+ 2 2) 5)
evaluates to false, so the expression "Chaos reigns"
is returned.
int-to-str
Use int-to-str
to represent an integer value
as a string in a specified base
.
The base can be any integer from 2 to 16, or 64 for unpadded base64URL representation.
Only positive values are allowed for base64URL conversion.
Basic syntax
To represent an integer value
as a string in a specified base
, use the following syntax:
(int-to-str base val)
Arguments
Use the following arguments to specify the base and integer value you want to convert using the int-to-str
Pact function.
Argument | Type | Description |
---|---|---|
base | integer | Specifies the base in which the integer value will be represented as a string. It can be any integer from 2 to 16, or 64 for unpadded base64URL representation. |
val | integer | Specifies the integer value to be converted into a string representation. |
Return value
The int-to-str
function returns the string representation of the integer value in the specified base.
Examples
The following examples demonstrate the use of int-to-str
in the Pact REPL:
pact>(int-to-str 16 65535)"FFFF"
pact>(int-to-str 16 65535)"FFFF"
In this example, the integer value 65535 is represented as a string in base 16, resulting in "FFFF".
pact>(int-to-str 64 43981)"XA"
pact>(int-to-str 64 43981)"XA"
In this example, the integer value 43981 is represented as a string in base 64 (unpadded base64URL), resulting in "XA".
is-charset
Use is-charset
to check whether a string conforms to a supported character set.
The character sets currently supported are CHARSET_LATIN1
(ISO-8859-1) and CHARSET_ASCII
(ASCII).
Support for additional sets, including those up through ISO 8859-5 supplement, will be added in the future.
Basic syntax
To check whether a string conforms to a specified character set, use the following syntax:
(is-charset charset input)
Arguments
Use the following arguments to specify the character set and input string you want to check using the is-charset
Pact function.
Argument | Type | Description |
---|---|---|
charset | integer | Specifies the character set to which the input string should conform. Currently supported values are 0 for 'CHARSET_LATIN1' (ISO-8859-1) and 1 for 'CHARSET_ASCII' (ASCII). |
input | string | Specifies the input string to be checked for conformity to the specified character set. |
Return value
The is-charset
function returns a boolean value indicating whether the input string conforms to the specified character set.
Examples
The following examples demonstrate the use of is-charset
in the Pact REPL:
pact>(is-charset CHARSET_ASCII "hello world")true
pact>(is-charset CHARSET_ASCII "hello world")true
In this example, the input string "hello world" conforms to the ASCII character set.
pact>(is-charset CHARSET_ASCII "I am nÖt ascii")false
pact>(is-charset CHARSET_ASCII "I am nÖt ascii")false
In this example, the input string "I am nÖt ascii" contains characters that are not part of the ASCII character set.
pact>(is-charset CHARSET_LATIN1 "I am nÖt ascii, but I am latin1!")true
pact>(is-charset CHARSET_LATIN1 "I am nÖt ascii, but I am latin1!")true
In this example, the input string "I am nÖt ascii, but I am latin1!" conforms to the ISO-8859-1 (Latin-1) character set.
length
Use length
to return the number of elements in a list, a string, or an object.
Basic syntax
To compute the length of a list, string, or object, use the following syntax:
(length arg)
(length arg)
Argument
Use the following argument to specify the value for which you want to compute the length using the length
Pact function.
Argument | Type | Description |
---|---|---|
arg | list, string, or object | Specifies the list, string, or object that you want to compute the length of. |
Return value
The length
function returns an integer representing the length of the specified list, string, or object.
Examples
The following example demonstrates calculating the length of the list [1, 2, 3]
in the Pact REPL:
pact> (length [1 2 3])3
pact> (length [1 2 3])3
The following example calculates the length of the string "abcdefgh"
, resulting in 8.
pact> (length "abcdefgh")8
pact> (length "abcdefgh")8
The following example calculates the length of the object { "a": 1, "b": 2 }
, resulting in 2.
pact> (length { "a": 1, "b": 2 })2
pact> (length { "a": 1, "b": 2 })2
list-module
Use list-modules
to list modules available for loading.
Basic syntax:
To list available modules for loading, use the following syntax:
list-modules
Return value:
The list-modules
function returns a list of strings representing the available modules for loading.
Examples:
The following example demonstrates the use of list-modules
in the Pact REPL:
pact> list-modules
pact> list-modules
In this example, the available modules for loading are listed.
list
Use list
to create a list from the specified elements. Note that this function is deprecated in Pact 2.1.1 with support for literal lists.
Basic syntax
To create a list from elements, use the following syntax:
(list elems)
Argument
Use the following argument to specify the elements from which you want to create a list using the list
Pact function.
Argument | Type | Description |
---|---|---|
elems | any | Specifies the elements to be included in the list. |
Return value
The list
function returns a list containing the specified elements.
Examples
The following example demonstrates the use of list
in the Pact REPL:
pact>(list 1 2 3)[1 2 3]
pact>(list 1 2 3)[1 2 3]
In this example, a list containing the elements 1, 2, and 3 is created using the list
function.
make-list
Use make-list
to create a list by repeating a specified value a certain number of times.
Basic syntax
To create a list by repeating a value
a specified number of times
, use the following syntax:
(make-list times value)
Arguments
Use the following arguments to specify the length of the list and the value to be repeated using the make-list
Pact function.
Argument | Type | Description |
---|---|---|
times | integer | Specifies the length of the list to be created. |
value | any | Specifies the value to be repeated to create the list. |
Return value
The make-list
function returns a list containing the specified value repeated the specified number of times.
Examples
The following example demonstrates the use of make-list
in the Pact REPL:
pact>(make-list 5 true)[true true true true true]
pact>(make-list 5 true)[true true true true true]
In this example, a list containing the value true
repeated 5 times is created using the make-list
function.
map
Use map
to apply an application function (app
) to each element in a list (list
), returning a new list of results.
You can use any data type for the list
argument as long as the first app
function can take that same data type.
By convention, data type notation like <a>
and <b>
are used to represent type-bound parameters that serve as input for functions and expressions or for generic arguments.
Basic syntax
To apply an application function to each element in a list, use the following syntax:
(map app list)
(map app list)
Arguments
Use the following arguments to specify the application function and the list of elements to be mapped using the map
Pact function.
Argument | Type | Description |
---|---|---|
app | function x:<b> -> <a> | Specifies the application function to be applied to each element in the list. |
list | [<b>] | Specifies the list of elements to be mapped. |
Return value
The map
function returns a new list containing the results of applying the application function to each element in the input list.
Examples
The following example demonstrates the use of map
in the Pact REPL:
pact>(map (+ 1) [1 2 3])[2 3 4]
pact>(map (+ 1) [1 2 3])[2 3 4]
In this example, the application function (+ 1)
is applied to each element in the list [1 2 3]
, resulting in a new list [2 3 4]
.
namespace
Use namespace
to set the current working environment to the specified namespace value.
After you declare the namespace you want to work with, all of the modules and functions you define are contained within that namespace.
You can access the modules and functions in a namespace by using their fully qualified name.
The fully-qualified name includes the namespace string as a prefix before the module name.
For example, if you declare a principal namespace such as n_14912521e87a6d387157d526b281bde8422371d1
for the module my-calculator
, you can call functions in the module using a fully-qualified name similar to the following:
n_14912521e87a6d387157d526b281bde8422371d1.my-calculator.add
If you call the namespace
function after the initial declaration, Pact creates a new namespace for all subsequent declarations until either the next namespace
call or the end of the transaction.
Prerequisites
You must define a namespace before you can set your working context to use the namespace
function. For information about defining a namespace, see define-namespace.
Basic syntax
To set the current namespace
to a specified value, use the following syntax:
(namespace namespace)
(namespace namespace)
Argument
Use the following argument to specify the namespace to be set using the namespace
Pact function.
Argument | Type | Description |
---|---|---|
namespace | string | Specifies the name of the namespace you want to use as your working context. |
Return value
The namespace
function returns the string representing the namespace that has been set.
Examples
The following example demonstrates the use of namespace
in a Pact script:
(namespace 'my-namespace)
(namespace 'my-namespace)
In this example, the current namespace is set to 'my-namespace'
. All subsequent expressions within the same transaction will be contained in this namespace until a new namespace is set or the transaction ends.
pact-id
Use pact-id
to return the ID if called during the current pact execution, failing if not.
Basic syntax
To return the ID during the current pact execution, use the following syntax:
(pact-id)
Return value
The pact-id
function returns a string representing the ID of the current pact execution.
Examples
The pact-id
function is called without any arguments. It returns the ID if called during the current pact execution.
(pact-id)
(pact-id)
In this example, pact-id
is called to retrieve the ID of the current pact execution.
pact-version
Use pact-version
to obtain the current Pact build version.
Basic syntax
To obtain the current Pact build version, use the following syntax:
(pact-version)
Return value
The pact-version
function returns a string representing the current Pact build version.
Examples
The pact-version
function is called without any arguments to obtain the current Pact build version.
pact>(pact-version)"5.0"
pact>(pact-version)"5.0"
In this example, (pact-version)
is called, which returns the current Pact build version as a string.
poseidon-hash-hack-a-chain
Use poseidon-hash-hack-a-chain
to compute the Poseidon Hash Function. Note: This is a reference version of the Poseidon hash function used by Hack-a-Chain.
Basic syntax
To compute the Poseidon Hash Function using the reference version, use the following syntax:
(poseidon-hash-hack-a-chain i j k l m n o p)
Arguments
Use the following arguments to specify the inputs for computing the Poseidon hash using the poseidon-hash-hack-a-chain
Pact function.
Argument | Type | Description |
---|---|---|
i , j , k , l , m , n , o , p | integer | Specifies the inputs for the Poseidon hash function. |
Return value
The poseidon-hash-hack-a-chain
function returns an integer representing the computed Poseidon hash.
Examples
The following examples demonstrate the use of poseidon-hash-hack-a-chain
in the Pact REPL:
pact>(poseidon-hash-hack-a-chain 1)pact>(poseidon-hash-hack-a-chain 1 2)pact>(poseidon-hash-hack-a-chain 1 2 3 4 5 6)pact>(poseidon-hash-hack-a-chain 1 2 3 4 5 6 7 8)
pact>(poseidon-hash-hack-a-chain 1)pact>(poseidon-hash-hack-a-chain 1 2)pact>(poseidon-hash-hack-a-chain 1 2 3 4 5 6)pact>(poseidon-hash-hack-a-chain 1 2 3 4 5 6 7 8)
In these examples, different sets of inputs are provided to compute the Poseidon hash using the reference version. The function returns the computed hash value as an integer.
read-decimal
Use read-decimal
to parse a key
string or number value from the top level of the message data body as a decimal.
Basic syntax
To parse a key
string as a decimal, use the following syntax:
(read-decimal key)
(read-decimal key)
Arguments
Use the following argument to specify the key
to be parsed as a decimal using the read-decimal
Pact function.
Argument | Type | Description |
---|---|---|
key | string | Specifies the key string or number value to parse as a decimal. |
Return value
The read-decimal
function returns the parsed value as a decimal.
Example
The following example demonstrates how to use the read-decimal
function in a Pact script.
This example parses the value specified for the amount
key in the body of a message as a decimal and transfers it from one account to another:
(defun exec () (transfer (read-msg "from") (read-msg "to") (read-decimal "amount")))
(defun exec () (transfer (read-msg "from") (read-msg "to") (read-decimal "amount")))
You can also use read-decimal
to read values from JSON object payloads.
read-integer
Use read-integer
to parse a key
string or number value from the top level of the message data body as an integer.
Basic syntax
To parse a key
string as an integer, use the following syntax:
(read-integer key)
(read-integer key)
Arguments
Use the following argument to specify the key
to be parsed as an integer using the read-integer
Pact function.
Argument | Type | Description |
---|---|---|
key | string | Specifies the key string or number value to parse as an integer. |
Return value
The read-integer
function returns the parsed value as an integer.
Example
The following example demonstrates how to use the read-integer
function in a Pact script.
This example parses the value specified for the age
key in the body of a message as an integer:
(read-integer 'age)
(read-integer 'age)
read-keyset
Use read-keyset
to read the specified key
from the message data body as a keyset.
A keyset consists of a list of keys (keylist
) and, optionally, a predicate function (predfun
).
Basic syntax
To read a key
from the message data body as a keyset, use the following syntax:
(read-keyset key)
(read-keyset key)
Arguments
Use the following argument to specify the key
to be read as a keyset using the read-keyset
Pact function.
Argument | Type | Description |
---|---|---|
key | string | Specifies the name of the key to be read from the message data body as a keyset. |
Return value
The read-keyset
function returns the keyset object corresponding to the specified key
string.
Example
The following example demonstrates how to use the read-keyset
function in a Pact script.
This example reads the object specified for the admin-keyset
key from the body of a message as the name of a keyset object:
(read-keyset 'admin-keyset)
(read-keyset 'admin-keyset)
read-msg
Use read-msg
to read a specific key
from the top level of the message data body, or to read the data body itself if a key
is not provided.
In reading the value, this function enforces its corresponding Pact type, such as string
, integer
, boolean
, list
, or object
.
Basic syntax
To read the value for a specified key
from the body of a message, use the following syntax:
(read-msg key)
(read-msg key)
To read the complete message data body, use the following syntax:
(read-msg)
(read-msg)
Arguments
Use the following argument to specify the key
to be read from the top level of the message data body using the read-msg
Pact function.
Argument | Type | Description |
---|---|---|
key | string | Specifies the key to be read from the message data body (optional). If you don't provide this argument, the function reads the entire data body. |
Return value
The read-msg
function returns the value corresponding to the specified key
from the message data body, or the entire data body if no key
is provided.
The data type for the return is its corresponding Pact type.
Example
The following example demonstrates how to use the read-msg
function in a Pact script.
This example reads the from
and to
keys from the data body of a message as strings and the amount
as a decimal:
(defun exec () (transfer (read-msg "from") (read-msg "to") (read-decimal "amount")))
(defun exec () (transfer (read-msg "from") (read-msg "to") (read-decimal "amount")))
This example illustrates how to use the read-msg
function to extract specific values from the body of a message for further processing in a Pact script.
read-string
Use read-string
to parse the specified key
string or number value from the top level of the message data body as a string
.
Basic syntax
To parse a key
string as a string, use the following syntax:
(read-string key)
(read-string key)
Arguments
Use the following argument to specify the key
to be parsed as a string using the read-string
Pact function.
Argument | Type | Description |
---|---|---|
key | string | Specifies the key string or number value to parse as a string. |
Return value
The read-string
function returns the parsed value as a string
.
Example
The following example demonstrates how to use the read-string
function in a Pact script.
This example parses the sender
from the data body of a message as a string:
(read-string 'sender)
(read-string 'sender)
remove
Use remove
to remove an entry associated with a specified key
from a specified object
.
Basic syntax
To remove an entry for a key
from an object
, use the following syntax:
(remove key {object})
(remove key {object})
Arguments
Use the following arguments to specify the key
and object
for removing an entry using the remove
Pact function.
Argument | Type | Description |
---|---|---|
key | string | Specifies the key for the entry to be removed from the object. |
object | object | Specifies the object from which to remove the entry. |
Return value
The remove
function returns the modified object with the entry associated with the specified key
removed.
Example
The following example demonstrates how to use the remove
function in the Pact REPL.
This example removes the entry for the bar
key from the given object:
pact> (remove "bar" { "foo": 1, "bar": 2 }){ "foo": 1 }
pact> (remove "bar" { "foo": 1, "bar": 2 }){ "foo": 1 }
resume
Use the resume
function to resume execution of a step in a defpact
.
This function binds to an object produced by the yield
function in the prior step of a pact
.
If the yield
function is executed on a different chain, the resume
function requires a simple payment verification (SPV) proof.
Basic syntax
To bind to a yielded object produced by a prior step execution, use the following syntax:
(resume binding)
(resume binding)
Arguments
Use the following argument to specify the binding
to be resumed using the resume
Pact function.
Argument | Type | Description |
---|---|---|
binding | object | Specifies the binding representing the yielded object from the prior step execution. |
Return value
The resume
function returns the value bound to the specified BINDING
.
Example
The following example demonstrates how to use the resume
function in a Pact script to bind to the yielded object sample
produced by the previous step in the execution of a pact:
(resume sample)
(resume sample)
The following example illustrates using yield
and resume
functions in defpact
steps:
(defpact deposit(sender:string receiver:string guard:guard amount:decimal) @doc "Deposit KDA from L1 to L2" @model [ (property (is-unit amount)) (property (is-principal sender)) (property (is-principal receiver)) ] (step (with-capability (LOCK_DEPOSIT sender) (let ((deposit-details:object{deposit-schema} { 'receiver : receiver , 'amount : amount , 'guard : guard } )) (lock-deposit sender amount) (enforce (validate-principal guard receiver) "Guard must be a principal") (yield deposit-details "crossnet:L2.2") ) ) ) (step (resume { 'receiver := receiver , 'amount := amount , 'guard := guard } (claim-deposit receiver guard amount) ) ) )
(defpact deposit(sender:string receiver:string guard:guard amount:decimal) @doc "Deposit KDA from L1 to L2" @model [ (property (is-unit amount)) (property (is-principal sender)) (property (is-principal receiver)) ] (step (with-capability (LOCK_DEPOSIT sender) (let ((deposit-details:object{deposit-schema} { 'receiver : receiver , 'amount : amount , 'guard : guard } )) (lock-deposit sender amount) (enforce (validate-principal guard receiver) "Guard must be a principal") (yield deposit-details "crossnet:L2.2") ) ) ) (step (resume { 'receiver := receiver , 'amount := amount , 'guard := guard } (claim-deposit receiver guard amount) ) ) )
reverse
Use reverse
to reverse the order of specified elements
in a list.
Basic syntax
To reverse a specified list of elements
, use the following syntax:
(reverse [elements])
(reverse [elements])
Arguments
Use the following argument to specify the elements
to be reversed using the reverse
Pact function.
Argument | Type | Description |
---|---|---|
elements | [any] | Specifies the elements in the list you want to be reversed. |
Return value
The reverse
function returns a new list with the elements in reverse order.
Example
The following example demonstrates how to use the reverse
function in the Pact REPL.
This example reverses the order of numbers in the list:
pact> (reverse [1 2 3])[3 2 1]
pact> (reverse [1 2 3])[3 2 1]
In the following example, the reverse
function reverses the order of strings in a list:
pact> (reverse ["lastname" "firstname" "age" "occupation"])["occupation" "age" "firstname" "lastname"]
pact> (reverse ["lastname" "firstname" "age" "occupation"])["occupation" "age" "firstname" "lastname"]
You can also reverse the order of objects in a list. For example:
(reverse [{"lastname":"pistolas","firstname": "lola"} {"lastname":"smith","firstname": "tim"}])[{"lastname": "smith","firstname": "tim"}{"lastname": "pistolas","firstname": "lola"}]
(reverse [{"lastname":"pistolas","firstname": "lola"} {"lastname":"smith","firstname": "tim"}])[{"lastname": "smith","firstname": "tim"}{"lastname": "pistolas","firstname": "lola"}]
This example illustrates how to use the reverse
function to reverse the order of elements in a list in Pact.
round
Use the round
function to round numbers to integers or decimals using banker's rounding.
The function returns an integer value if you don't specify precision
as an argument.
If you specify the precision
argument, the function returns a decimal value with the specified precision.
Basic syntax
To round a decimal value to the nearest integer, use the following syntax:
(round number)
(round number)
To round a decimal value to a specified precision, use the following syntax:
(round number precision)
(round number precision)
Arguments
Use the following arguments to specify the value to be rounded and, optionally, the precision to round to using the round
Pact function.
Argument | Type | Description |
---|---|---|
number | decimal | Specifies the decimal value to be rounded. |
precision | integer | Specifies the precision to round to, if applicable (optional). |
Return value
If no precision is specified, the round
function returns the rounded value as an integer
.
If precision is specified, it returns the rounded value as a decimal
value.
Examples
The following examples demonstrate the usage of the round
function within the Pact REPL.
To round the decimal value 3.5 to the nearest integer:
pact> (round 3.5)4
pact> (round 3.5)4
To round the decimal value 100.15234 to 2 decimal places:
pact> (round 100.15234 2)100.15
pact> (round 100.15234 2)100.15
sort
Use sort
to sort a list of primitive values based on the values themselves or a list of objects based on specific fields within the objects.
If you're sorting primitive values, they are sorted in ascending numerical or alphabetical order.
Basic syntax
Because sort
is an overloaded function, there are two ways to use it.
To sort a list of primitive values, use the following syntax:
(sort [primitives])
(sort [primitives])
To sort a list of objects based on specific fields, use the following syntax:
(sort [fields] [{object1} {object2} ...])
(sort [fields] [{object1} {object2} ...])
Arguments
Use the following arguments to specify the values or fields for sorting using the sort
Pact function.
Argument | Type | Description |
---|---|---|
primitives | [integer, decimal, or string] | Specifies the list of primitive values to be sorted. |
fields | [list] | Specifies the list of fields within objects to be used for sorting. |
object1 | object | Specifies more or more objects to be sorted using the fields parameter. |
Return value
The sort
function returns a sorted list of values or objects based on the specified sorting criteria.
Examples
The following examples illustrate how to use the sort
function to sort lists of values or objects in Pact.
The following example demonstrates how to the sort a list of primitive values [3, 1, 2]
using of the sort
function:
pact> (sort [3 1 2])[1, 2, 3]
pact> (sort [3 1 2])[1, 2, 3]
If you sort a list of string primitive values, they are sorted in alphabetical order. For example:
pact> (sort ["second" "day" "minute" "hour"])["day" "hour" "minute" "second"]
pact> (sort ["second" "day" "minute" "hour"])["day" "hour" "minute" "second"]
To sort a list of objects based on the 'age
field:
pact> (sort ['age] [{'name: "Lin", 'age: 30} {'name: "Val", 'age: 25} {'name: "Kai", 'age: 21}])[{"name": "Kai","age": 21} {"name": "Val","age": 25} {"name": "Lin","age": 30}]
pact> (sort ['age] [{'name: "Lin", 'age: 30} {'name: "Val", 'age: 25} {'name: "Kai", 'age: 21}])[{"name": "Kai","age": 21} {"name": "Val","age": 25} {"name": "Lin","age": 30}]
str-to-int
Use str-to-int
to compute the integer value of the string str
interpreted in base 10, or in a specified base
,if provided.
The str
argument can be up to 512 characters.
If you specify the base
argument, it must be between 2 and 16, or 64 to perform unpadded base64url conversion.
Each digit in the str
argument must be in the correct range for the base.
Basic syntax
To compute the integer value of a string in base 10, use the following syntax:
(str-to-int str)
(str-to-int str)
To compute the integer value of a string in a specified base, use the following syntax:
(str-to-int base str)
(str-to-int base str)
Arguments
Use the following arguments to specify the string value and, optionally, the base for conversion using the str-to-int
Pact function.
Argument | Type | Description |
---|---|---|
str | string | Specifies the string value to be converted to an integer. |
base | integer | Specifies the base in which to interpret the string value (optional). Must be between 2 and 16, or 64 for base64url encoding without padding. |
Return value
The str-to-int
function returns the integer
value computed from the input string str
.
Examples
The following examples demonstrate how to use the str-to-int
function to compute the integer value of a string in the Pact REPL.
To compute the integer value of the string "123456" interpreted in base 10:
pact> (str-to-int "123456")123456
pact> (str-to-int "123456")123456
To compute the integer value of the string "abcdef123456" interpreted in base 16:
pact> (str-to-int 16 "abcdef123456")188900967593046
pact> (str-to-int 16 "abcdef123456")188900967593046
To compute the integer value of the string "spirekey" interpreted in base 64 for base64url conversion without padding:
pact> (str-to-int 64 "spirekey")196368781690802
pact> (str-to-int 64 "spirekey")196368781690802
str-to-list
Use str-to-list
to convert a specified string
into a list where each element is a single-character string.
Converting a string into a list can be useful for performing other more complex string manipulation tasks.
Basic syntax
To convert a string into a list of single-character strings, use the following syntax:
(str-to-list string)
(str-to-list string)
Arguments
Use the following argument to specify the string
to be converted into a list of single-character strings using the str-to-list
Pact function.
Argument | Type | Description |
---|---|---|
string | string | Specifies the string to be converted into a list. |
Return value
The str-to-list
function returns a list where each element represents a single character from the input string
.
Examples
The following examples demonstrate how to use the str-to-list
function within the Pact REPL.
To convert the string "hello" into a list of single-character strings:
pact> (str-to-list "hello")["h", "e", "l", "l", "o"]
pact> (str-to-list "hello")["h", "e", "l", "l", "o"]
To concatenate spaces between each character in the string "abcde":
(concat (map (+ " ") (str-to-list "abcde")))" a b c d e"
(concat (map (+ " ") (str-to-list "abcde")))" a b c d e"
take
Use the take
function to retrieve a specified number of values from a list (or string), or entries with keys specified in keys
from an object.
If the count
argument is negative, values are taken from the end of the list.
If the count
exceeds the interval (-2^63,2^63), it is truncated to that range.
Basic syntax
Because take
is an overloaded function, there are two ways to use it.
To retrieve a specified number of values from a list or a string, use the following syntax:
(take count [list])
(take count [list])
To retrieve entries with specified keys from an object, use the following syntax:
(take keys {object})
(take keys {object})
Arguments
Use the following arguments to specify the number of values to retrieve and the list or object to retrieve them from using the take
Pact function.
Argument | Type | Description |
---|---|---|
count | integer | Specifies the number of values to retrieve from the list or string. If negative, values are taken from the end. |
list | [integer, decimal, or string] or string | Specifies the list or string from which to retrieve values. |
keys | [string] | Specifies the keys for the information you want to retrieve from the specified object. |
object | object | Specifies the object from which to retrieve entries. |
Return value
The take
function returns a subset of values retrieved from the list or from the object based on the specified count or number of keys.
Examples
The following examples demonstrate how to use the take
function in the Pact REPL.
To retrieve the first two characters from the string "abcd":
pact> (take 2 "abcd")"ab"
pact> (take 2 "abcd")"ab"
To retrieve the last three values from the list [1, 2, 3, 4, 5]:
pact> (take (- 3) [1 2 3 4 5])[3, 4, 5]
pact> (take (- 3) [1 2 3 4 5])[3, 4, 5]
To retrieve entries with the key 'name
from the object { 'name: "Vlad", 'active: false }
:
(take ['name] { 'name: "Vlad", 'active: false, 'age: 34 }){"name": "Vlad"}
(take ['name] { 'name: "Vlad", 'active: false, 'age: 34 }){"name": "Vlad"}
try
Use the try
function to attempt a pure action, returning a default value in the case of failure.
Pure functions and pure expressions perform operations that produce a resulting value with no side effects.
Pure functions always return identical results for identical arguments. Pure expressions don't allow mutable variables reference arguments, or input and output operations.
Unlike impure expressions that support reading and writing to tables and working with non-deterministic state, pure expressions:
- Don't write to memory or perform input or output operations.
- Don't work with non-deterministic state.
Basic syntax
To attempt a pure action and return a default value if the action fails, use the following syntax:
(try default ACactionTION)
(try default ACactionTION)
Arguments
Use the following arguments to specify the default value and the action to be attempted using the try
Pact function.
Argument | Type | Description |
---|---|---|
default | any | Specifies the default value to be returned if the action fails. |
action | any | Specifies the action to be attempted. |
Return value
The try
function returns the result of the attempted action.
If the action fails, it returns the specified default value.
Examples
The following example demonstrates how to use the try
function in the Pact REPL.
This example attempts to use the enforce
function to specify a condition.
If the condition fails, the try
function returns the default value 3
:
pact> (try 3 (enforce (= 1 2) "this will definitely fail"))3
pact> (try 3 (enforce (= 1 2) "this will definitely fail"))3
If the enforce
function specifies a condition that succeeds, the try function returns the result.
In this case, the result is true
:
(try 3 (enforce (= 1 1) "this will definitely fail"))true
(try 3 (enforce (= 1 1) "this will definitely fail"))true
In the following example, the default value is a string:
(try "this enforce fails" (enforce (= 2 1) "this will definitely fail"))"this enforce fails"
(try "this enforce fails" (enforce (= 2 1) "this will definitely fail"))"this enforce fails"
tx-hash
Use tx-hash
to get the hash of the current transaction as a string.
Basic syntax
To obtain the hash of the current transaction, use the following syntax:
(tx-hash)
(tx-hash)
Return value
The tx-hash
function returns the hash of the current transaction as a string.
Examples
The following example demonstrates how to use the tx-hash
function in the Pact REPL.
This example gets the hash of the current transaction:
(tx-hash)"DldRwCblQ7Loqy6wYJnaodHl30d3j3eH-qtFzfEv46g"
(tx-hash)"DldRwCblQ7Loqy6wYJnaodHl30d3j3eH-qtFzfEv46g"
typeof
Use typeof
to return the data type of the specified value
.
The data type of the specified value is returned
as a string.
Basic syntax
To determine the data type for a value
, use the following syntax:
(typeof value)
Argument
Use the following argument to specify the value for which to determine the type using the typeof
Pact function.
Argument | Type | Description |
---|---|---|
value | any | Specifies the value for which to determine the type. |
Return value
The typeof
function returns the data type of the provided value
as a string.
Examples
The following example demonstrates how to use the typeof
function in the Pact REPL.
This example returns the data type of the value 'hello
:
pact> (typeof 'hello)"string"
pact> (typeof 'hello)"string"
The following example returns the data type of the value 8
:
pact> (typeof 8)"integer"
pact> (typeof 8)"integer"
The following example returns the data type of the value 4.3
:
pact> (typeof 4.3)"decimal"
pact> (typeof 4.3)"decimal"
where
Use the where
function to apply a specified application function (app
) to a field (field
) to evaluate the field value (value
).
The function returns a boolean value based on the result of the application.
This function is most often used in conjunction with filter
and select
operations.
Basic syntax
To apply an application function to a field
in a value, use the following syntax:
(where field app)
(where field app)
Arguments
Use the following arguments to specify the field, application function, and value for evaluation using the where
Pact function.
Argument | Type | Description |
---|---|---|
field | string | Specifies the field in the value to be evaluated. |
app | function | Specifies the application function to be applied to the field. |
value | object:<{row}> | Specifies the value containing the field to be evaluated. |
Return value
The where
function returns a boolean
value based on the result of applying the specified application function to the field in the value.
Examples
The following example demonstrates how to use the where
function in the Pact REPL.
This example applies a condition for filtering a list of objects where the "age"
field value is less than 20
:
(filter (where 'age (> 20)) [{'name: "Mary",'age: 30} {'name: "Juan",'age: 15}])[{"age":15, "name":"Juan"}]
(filter (where 'age (> 20)) [{'name: "Mary",'age: 30} {'name: "Juan",'age: 15}])[{"age":15, "name":"Juan"}]
yield
Use yield
to yield an object for use with the resume
function in the subsequent Pact step.
Optionally, you can specify a target chain for executing the next step using automated a simplified payment verification (spv) endorsement-based dispatch.
Basic syntax
To yield an object
for use with the resume
function, use the following syntax:
(yield object [target-chain])
(yield object [target-chain])
Arguments
Use the following arguments to specify the object and, optionally, the target chain for executing the subsequent step using the yield
Pact function.
Argument | Type | Description |
---|---|---|
object | object | Specifies the object to be yielded for use with 'resume'. |
target-chain | string | Specifies the chain ID on which the subsequent step should execute (optional). |
Return value
The yield
function returns the yielded object.
Examples
The following examples demonstrate how to use the yield
function in a Pact script.
In the following example, the yield
function creates an object with one key and value that can be passed to the resume
function,
(yield { "amount": 100.0 })
(yield { "amount": 100.0 })
Optionally, you can specify a target chain for resuming the transaction. For example, to set the target chain to chain 8:
(yield { "amount": 100.0 } "8")
(yield { "amount": 100.0 } "8")
The following example illustrates using yield
and resume
functions in defpact
steps:
(defpact copy-account:string(account:string target:string) (step (with-capability (COPY_ACCOUNT account) (with-read guard-lookup-table account { 'webauthn-guard-name := guard-name } (webauthn-guard.copy-account guard-name target) (let ((yield-data:object{copy-account-schema} { 'guard-name : guard-name })) (yield yield-data target) ) ) ) ) (step (resume { 'guard-name := guard-name } (continue (webauthn-guard.copy-account guard-name target)) (write guard-lookup-table target { 'webauthn-guard-name : guard-name } ) (coin.create-account (get-account-name guard-name) (get-account-guard guard-name)) ) ) )
(defpact copy-account:string(account:string target:string) (step (with-capability (COPY_ACCOUNT account) (with-read guard-lookup-table account { 'webauthn-guard-name := guard-name } (webauthn-guard.copy-account guard-name target) (let ((yield-data:object{copy-account-schema} { 'guard-name : guard-name })) (yield yield-data target) ) ) ) ) (step (resume { 'guard-name := guard-name } (continue (webauthn-guard.copy-account guard-name target)) (write guard-lookup-table target { 'webauthn-guard-name : guard-name } ) (coin.create-account (get-account-name guard-name) (get-account-guard guard-name)) ) ) )
zip
Use the zip
function to combine two lists using a specified function func
into a new list.
The length of the resulting list is determined by the length of the shortest input list.
Basic syntax
To combine two lists with a specified function f
into a new list, use the following syntax:
(zip func list1 list2)
(zip func list1 list2)
Arguments
Use the following arguments to specify the function and the lists that you want to combine using the zip
Pact function.
Argument | Type | Description |
---|---|---|
func | function | Specifies the function to combine elements from the two lists. |
list1 | [any] | Specifies the first list to be combined. |
list2 | [any] | Specifies the second list to be combined. |
Return value
The zip
function returns a new list containing elements combined from the input lists according to the specified function func
.
Examples
The following examples demonstrate how to use the zip
function in the Pact REPL.
This example combines two lists of numbers using the specified addition (+) function a new list:
pact> (zip (+) [1 2 3 4] [4 5 6 7])[5, 7, 9, 11]
pact> (zip (+) [1 2 3 4] [4 5 6 7])[5, 7, 9, 11]
The following example combines two lists of numbers using the specified subtraction (-) function to create a new list:
pact>(zip (-) [1 2 3 4] [4 5 6])[-3, -3, -3]
pact>(zip (-) [1 2 3 4] [4 5 6])[-3, -3, -3]
The following example illustrate combining two lists using the multiplication (*) function to create a new list with its length determined by input list with the fewest items
pact> (zip (*) [1 2 3 ] [4 5 6 7 8])[4 10 18]
pact> (zip (*) [1 2 3 ] [4 5 6 7 8])[4 10 18]