docs
Search…
Query Price
Current dfinance VM implementation supports querying the price for the provided ticker thanks to Coins module:
1
address 0x1 {
2
/// Enum-like module to make generic type-matching possible, every coin which is
3
/// officially supported by blockchain (or peg-zone specifically) is added here.
4
/// Ideally this module should be auto-generated and rarely updated via consensus
5
module Coins {
6
struct ETH {}
7
struct BTC {}
8
struct USDT {}
9
10
resource struct Price<Curr1, Curr2> {
11
value: u128
12
}
13
14
public fun get_price<Curr1, Curr2>(): u128 acquires Price {
15
borrow_global<Price<Curr1, Curr2>>(0x1).value
16
}
17
18
public fun has_price<Curr1, Curr2>(): bool {
19
exists<Price<Curr1, Curr2>>(0x1)
20
}
21
}
22
}
Copied!
There are two functions, get_price and has_price, both require two generics (pairs) to make a call, e.g.: BTC_USDT, ETH_USDT, XFI_BTC.
Let's try to query BTC_USDT price:
1
let btc_usd = Coins::get_price<Coins::BTC, Coins::USDT>();
Copied!
As script it looks so:
1
script {
2
use 0x1::Coins;
3
4
fun main() {
5
let _ = Coins::get_price<Coins::BTC, Coins::USDT>();
6
}
7
}
Copied!
Also, you can check, if pair exists:
1
script {
2
use 0x1::Coins;
3
4
fun main() {
5
// If BTC_USDT pair doesn't exist - throw error with code 101.
6
assert(Coins::has_price<Coins::BTC, Coins::USDT>(), 101);
7
}
8
}
Copied!

Price

By default returned u128 price has reserved 8 decimals places.
Means price for ETH_USDT as 100.02 will be presented as 10002000000.
To see an example look at our API, ETH_USDT part, how price presented there.

Write a script

Let's write a script that will take BTC_USDT price and will emit an event with this ticker's price:
1
script {
2
use 0x1::Event;
3
use 0x1::Coins;
4
5
fun main(account: &signer) {
6
let price = Coins::get_price<Coins::BTC, Coins::USDT>();
7
8
Event::emit(account, price);
9
}
10
}
Copied!
Compile the script and execute.
You can query results by transaction id to see how events with price fired.

Usage in module

Similarly, you can write your module, that will use the price from oracles.
Something like:
1
module PriceRequest {
2
use 0x1::Coins;
3
4
public fun get_eth_usdt_price(): u128 {
5
Coins::get_price<Coins::ETH, Coins::USDT>()
6
}
7
}
Copied!
And then just use it in your scripts.
Last modified 9mo ago