contract_name
stringlengths 1
40
| code_body
stringlengths 0
100k
| txid
stringlengths 66
66
| block_height
int32 0
165k
| status
stringclasses 3
values |
---|---|---|---|---|
quotes-v1 | (define-constant owner tx-sender)
(define-non-fungible-token quote uint)
(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
(define-data-var last-id uint u0)
;; Last token ID, limited to uint range
(define-read-only (get-last-token-id)
(ok (var-get last-id)))
(define-map metadata uint (string-utf8 2048))
;; URI for metadata associated with the token
(define-read-only (get-token-uri (id uint)) (ok none))
(define-read-only (get-owner (id uint))
(ok (nft-get-owner? quote id)))
;; Owner of a given token identifier
(define-public (transfer (id uint) (sender principal) (recipient principal))
(nft-transfer? quote id sender recipient))
(define-public (add-quote (quote-text (string-utf8 2048)))
(let (
(last-token-id (var-get last-id))
(new-id (+ last-token-id u1)))
(map-insert metadata new-id quote-text)
(var-set last-id new-id)
(print quote-text)
(nft-mint? quote new-id tx-sender)))
(define-read-only (get-quote-by-id (id uint))
(ok (map-get? metadata id))) | 0xea20f35f843b65fb24c29ee0128dae7e8b5e3b76af85aa25a3ad104cddadc873 | 11,876 | success |
pool-registry-v1 | ;; Two traits pool contracts should implement
;;
;; The genesis pox contract implements pool-trait
;; Pools that run as a contract can implement pool-trait-ext with additional information from the user
(define-trait pool-trait ((delegate-stx (uint principal (optional uint)
(optional (tuple (hashbytes (buff 20)) (version (buff 1))))) (response bool int))))
(define-trait pool-trait-ext ((delegate-stx (uint principal (optional uint)
(optional (tuple (hashbytes (buff 20)) (version (buff 1))))
(tuple (hashbytes (buff 20)) (version (buff 1)))
uint) (response bool int))))
(define-trait pool-trait-ext2 ((delegate-stx (uint principal (optional uint)
(optional (tuple (hashbytes (buff 20)) (version (buff 1))))
(tuple (hashbytes (buff 20)) (version (buff 1)))
uint) (response bool {kind: (string-ascii 32), code: uint}))))
(define-constant ERR_INVALID_PAYOUT u1)
(define-constant ERR_INVALID_STATUS u2)
(define-constant ERR_NAME_REGISTERED u3)
(define-constant ERR_NATIVE_FUNCTION_FAILED u4)
(define-constant ERR_NAME_NOT_ON_CHAIN u5)
(define-constant ERR_REGISTRATION u6)
(define-constant ERR_NAME_PRICE u7)
(define-constant ERR_PERMISSION_DENIED u403)
(define-constant ERR_NAME_NOT_REGISTERED u404)
;; list of registered pools
(define-map registry
uint
(tuple
(name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract (optional principal))
(extended-contract (optional principal))
(extended2-contract (optional principal))
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint)))
;; list of means of payout
(define-map payouts
(string-ascii 5)
(tuple
(name (string-ascii 80) )
))
(define-map statuses
uint
(string-ascii 80)
)
(define-map lookup
principal
uint)
(define-data-var last-id uint u0)
(define-private (get-id? (delegatee principal))
(map-get? lookup delegatee))
(define-private (get-owner (name (tuple (namespace (buff 20)) (name (buff 48)))))
(match (contract-call? 'SP000000000000000000002Q6VF78.bns name-resolve (get namespace name) (get name name))
entry (some (get owner entry))
error none))
(define-private (can-register (name (tuple (namespace (buff 20)) (name (buff 48)))))
(match (contract-call? 'SP000000000000000000002Q6VF78.bns can-name-be-registered (get namespace name) (get name name))
result result
error false))
(define-private (can-receive-name (user principal))
(match (contract-call? 'SP000000000000000000002Q6VF78.bns can-receive-name user)
result result
error false))
(define-private (register-name (name (tuple (namespace (buff 20)) (name (buff 48)))) (user principal))
(match (print (contract-call? 'SP000000000000000000002Q6VF78.bns name-preorder (hash160 (concat (concat (concat (get name name) 0x2e) (get namespace name)) 0x00)) (unwrap! (get-name-price name) (err ERR_NAME_PRICE))))
result-preorder
(match (print (contract-call? 'SP000000000000000000002Q6VF78.bns name-register (get namespace name) (get name name) 0x00 0x00 ))
result-register (ok true)
error (err (to-uint error)))
error (err (to-uint error))))
(define-private (get-name-price (name (tuple (namespace (buff 20)) (name (buff 48)))))
(print (contract-call? 'SP000000000000000000002Q6VF78.bns get-name-price (get namespace name) (get name name))))
(define-private (to-response (success bool))
(if success
(ok true)
(err ERR_NATIVE_FUNCTION_FAILED)))
(define-public (add-payout (symbol (string-ascii 5)) (name (string-ascii 80)))
(ok (map-insert payouts symbol {name: name})))
(define-public (add-status (status uint) (name (string-ascii 80)))
(ok (map-insert statuses status name)))
;; register a new pool that implements the simple pool trait like genesis "pox" contract.
(define-public (register (name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract <pool-trait>)
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))
(base-register name delegatee pox-address url (some (contract-of contract)) none none minimum-ustx locking-period payout date-of-payout fees status))
;; register a new pool that implements the extended pool trait
(define-public (register-ext (name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract <pool-trait-ext>)
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))
(base-register name delegatee pox-address url none (some (contract-of contract)) none minimum-ustx locking-period payout date-of-payout fees status))
;; register a new pool that implements the extended pool trait 2
(define-public (register-ext2 (name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract <pool-trait-ext2>)
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))
(base-register name delegatee pox-address url none none (some (contract-of contract)) minimum-ustx locking-period payout date-of-payout fees status))
(define-private (base-register (name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract (optional principal))
(extended-contract (optional principal))
(extended2-contract (optional principal))
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))
(let ((id (+ (get-last-id) u1)))
(unwrap! (map-get? payouts payout) (err ERR_INVALID_PAYOUT))
(unwrap! (map-get? statuses status) (err ERR_INVALID_STATUS))
(match (get-owner name)
owner (asserts! (is-eq tx-sender owner) (err ERR_PERMISSION_DENIED))
(begin
(asserts! (and (can-receive-name tx-sender) (can-register name)) (err ERR_NAME_NOT_ON_CHAIN))
(unwrap! (register-name name tx-sender) (err ERR_REGISTRATION))))
(if (is-none (map-get? lookup delegatee))
(begin
(var-set last-id id)
(map-insert registry id
{name: name,
delegatee: delegatee,
pox-address: pox-address,
url: url,
contract: contract,
extended-contract: extended-contract,
extended2-contract: extended2-contract,
minimum-ustx: minimum-ustx,
locking-period: locking-period,
payout: payout,
date-of-payout: date-of-payout,
fees: fees,
status: status})
(map-insert lookup delegatee id)
(ok id))
(err ERR_NAME_REGISTERED))))
(define-public (update (name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract <pool-trait>)
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))
(base-update name delegatee pox-address url (some (contract-of contract)) none none minimum-ustx locking-period payout date-of-payout fees status))
(define-public (update-ext (name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract <pool-trait-ext>)
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))
(base-update name delegatee pox-address url none (some (contract-of contract)) none minimum-ustx locking-period payout date-of-payout fees status))
(define-public (update-ext2 (name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract <pool-trait-ext2>)
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))
(base-update name delegatee pox-address url none none (some (contract-of contract)) minimum-ustx locking-period payout date-of-payout fees status))
(define-private (base-update (name (tuple (namespace (buff 20)) (name (buff 48))))
(delegatee principal)
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(contract (optional principal))
(extended-contract (optional principal))
(extended2-contract (optional principal))
(minimum-ustx (optional uint))
(locking-period (list 12 uint))
(payout (string-ascii 5))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))
(if (is-eq tx-sender (unwrap! (get-owner name) (err ERR_NAME_NOT_ON_CHAIN)))
(let ((id (unwrap! (get-id? delegatee) (err ERR_NAME_NOT_REGISTERED))))
(unwrap! (map-get? payouts payout) (err ERR_INVALID_PAYOUT))
(unwrap! (map-get? statuses status) (err ERR_INVALID_STATUS))
(to-response (map-set registry id
{name: name,
delegatee: delegatee,
pox-address: pox-address,
url: url,
contract: contract,
extended-contract: extended-contract,
extended2-contract: extended2-contract,
minimum-ustx: minimum-ustx,
locking-period: locking-period,
payout: payout,
date-of-payout: date-of-payout,
fees: fees,
status: status})))
(err ERR_PERMISSION_DENIED)))
(define-read-only (get-last-id) (var-get last-id))
(define-read-only (get-pool-by-delegatee (delegatee principal))
(map-get? registry (unwrap! (get-id? delegatee) none)))
(define-read-only (get-pool (pool-id uint))
(map-get? registry pool-id)
)
(define-private (add-registry-data (pool-id uint) (result (list 20 (optional (tuple
(contract (optional principal))
(delegatee principal)
(extended-contract (optional principal))
(extended2-contract (optional principal))
(locking-period (list 12 uint))
(minimum-ustx (optional uint))
(name (tuple (name (buff 48)) (namespace (buff 20))))
(payout (string-ascii 5))
(pox-address (list 12 (tuple (hashbytes (buff 20)) (version (buff 1)))))
(url (string-ascii 250))
(date-of-payout (string-ascii 80))
(fees (string-ascii 80))
(status uint))))))
(unwrap-panic (as-max-len? (append result (map-get? registry pool-id)) u20)))
(define-read-only (get-pools (pool-ids (list 20 uint)))
(fold add-registry-data pool-ids (list)))
(add-payout "BTC" "Bitcoin")
(add-payout "STX" "Stacks")
(add-status u0 "in development")
(add-status u1 "in production")
(add-status u11 "open for stacking")
(add-status u21 "closed for stacking")
(add-status u99 "retired")
| 0x14f8ca3a28ed6f2c775473cef3cb635b3e7f56903310fe5c7a9a73c9e4f59499 | 12,077 | success |
ashamed-copper-mandrill | ;; hello-world contract
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SP162D87CY84QVVCMJKNKGHC7GGXFGA0TAR9D0XJW)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event! Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store {key: (buff 32)} {value: (buff 32)})
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store {key: key})
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store {key: key} {value: value})
(ok u1))) | 0x82760f25fa13279eff30d41c6d49543bc2b615ebe93b48d2aca327bd90724bfb | 12,084 | success |
coming-green-mouse | ;; hello-world contract
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SP162D87CY84QVVCMJKNKGHC7GGXFGA0TAR9D0XJW)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event! Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store {key: (buff 32)} {value: (buff 32)})
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store {key: key})
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store {key: key} {value: value})
(ok u1))) | 0x793a32649df9df03dcf4249aa7e9b88cd8d4032cd0fb66713262038ec6452dbc | 12,084 | success |
raw-crimson-bird | ;; hello-world contract
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SP162D87CY84QVVCMJKNKGHC7GGXFGA0TAR9D0XJW)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event! Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store {key: (buff 32)} {value: (buff 32)})
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store {key: key})
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store {key: key} {value: value})
(ok u1))) | 0x09732187f4f7efbfbebdd069ab2b24e1f0620af112d2bf4b4d92b5d775444bc5 | 12,084 | success |
puzzled-gold-stork | ;; hello-world contract
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SP162D87CY84QVVCMJKNKGHC7GGXFGA0TAR9D0XJW)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event! Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store {key: (buff 32)} {value: (buff 32)})
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store {key: key})
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store {key: key} {value: value})
(ok u1))) | 0x55d66e0ca6fcf2972f5c77994d282a2690280d1fd2c93669af47089ec9b86da5 | 12,084 | success |
balanced-magenta-coral | ;; hello-world contract
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SP38J10VQRENJWK6NY2CX95D8RKXSYTCDJT8EDYYX)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event! Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store {key: (buff 32)} {value: (buff 32)})
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store {key: key})
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store {key: key} {value: value})
(ok u1))) | 0x620c1eb84dfd85e5172d4da9c89d93afab10f10cac7a0e995b5b6361a51e14c1 | 12,567 | success |
clovers | (define-fungible-token clovers u1000) | 0x48a995f69666478561c85a8c00cc4f5be88478c198e81df55ce52054c4fbcf2d | 13,274 | success |
pleased-coffee-baboon | (define-non-fungible-token boom uint)
(define-data-var last-id uint u0)
(define-data-var last-series-id uint u0)
(impl-trait .nft-trait.nft-trait)
;;(impl-trait 'ST22HQ6YT0NAHB42F6X8PGZVA70S2XNB7KF03ZABX.sip-009-nft-trait.nft-trait)
;; each nft id to series id
(define-map meta uint {series-id: uint, number: uint})
(define-map index-by-series-item
(tuple
(series-id uint)
(number uint))
uint)
(define-map series-meta uint
{
creator: principal,
creator-name: (optional (tuple (namespace (buff 20)) (name (buff 48)))),
series-name: (string-utf8 80),
count: uint,
uri: (string-ascii 256),
mime-type: (string-ascii 129),
hash: (buff 64)
})
(define-private (owns-name (user principal) (username (tuple (namespace (buff 20)) (name (buff 48)))))
(match (contract-call? 'ST000000000000000000002AMW42H.bns name-resolve (get namespace username) (get name username))
details (is-eq user (get owner details))
error false
)
)
(define-private (inc-last-series-id)
(let ((series-id
(+ u1 (var-get last-series-id))))
(begin
(var-set last-series-id series-id)
series-id
)))
(define-private (is-creator (creator principal)
(creator-name (optional (tuple (namespace (buff 20)) (name (buff 48))))))
(and
(or (is-eq creator tx-sender) (is-eq creator contract-caller))
(match creator-name
username (owns-name creator username)
true )))
(define-private (same-series-meta (series-id uint) (creator principal)
(creator-name (optional (tuple (namespace (buff 20)) (name (buff 48)))))
(series-name (string-utf8 80)) (uri (string-ascii 256)))
(match (get-series-meta-raw? series-id)
entry (and
(or (is-eq creator tx-sender) (is-eq creator contract-caller))
(is-eq creator (get creator entry))
(is-eq creator-name (get creator-name entry))
(is-eq series-name (get series-name entry))
(is-eq uri (get uri entry)))
false
)
)
(define-private (update-series-meta
(series-id uint)
(creator principal)
(creator-name (optional (tuple (namespace (buff 20)) (name (buff 48)))))
(series-name (string-utf8 80))
(uri (string-ascii 256))
(mime-type (string-ascii 129))
(hash (buff 64))
(count uint)
)
(match (map-get? series-meta series-id)
entry (map-set series-meta series-id
(merge entry {count: (+ count (get count entry)),}))
(map-insert series-meta series-id
{creator: creator,
creator-name: creator-name,
series-name: series-name,
count: count,
hash: hash,
uri: uri,
mime-type: mime-type})))
(define-private (mint-boom (index uint)
(context {creator: principal, series-id: uint, index: uint, recipient: principal}))
(let (
(id (+ u1 (var-get last-id)))
(series-id (get series-id context))
(fold-index (get index context)))
(unwrap-panic (nft-mint? boom id (get recipient context)))
(asserts-panic (var-set last-id id))
(asserts-panic
(map-insert meta id {number: fold-index, series-id: series-id}))
(asserts-panic
(map-insert index-by-series-item {series-id: series-id, number: fold-index} id))
(print fold-index)
(merge context {index: (+ u1 fold-index)})))
(define-public (mint-series
(creator principal)
(creator-name (optional (tuple (namespace (buff 20)) (name (buff 48)))))
(existing-series-id (optional uint))
(series-name (string-utf8 80))
(series-uri (string-ascii 256))
(series-mime-type (string-ascii 129))
(hash (buff 64))
(copies (list 7500 uint))
(recipient (optional principal)))
(let ((series-id (match existing-series-id
id (begin
(asserts! (same-series-meta id creator creator-name series-name series-uri) (err {kind: "permission-denied", code: u0}))
id)
(begin
(asserts! (is-creator creator creator-name) (err {kind: "not-creator", code: u1}))
(inc-last-series-id))))
(series (get-series-meta-raw? series-id))
(series-index (match series
series-data (get count series-data)
u0)))
(update-series-meta series-id creator creator-name series-name series-uri series-mime-type hash (len copies))
(let ((context
(fold mint-boom copies {creator: creator, series-id: series-id, index: (+ u1 series-index), recipient: (default-to creator recipient)})))
(ok {count: (+ series-index (len copies)), series-id: series-id}))))
(define-public (transfer (id uint) (sender principal) (recipient principal))
(if (or (is-eq sender tx-sender) (is-eq sender contract-caller))
(match (nft-transfer? boom id sender recipient)
success (ok success)
error (err {kind: "nft-transfer-failed", code: error}))
(err {kind: "permission-denied", code: u4})))
(define-public (burn (id uint))
(match (get-owner-raw? id)
owner (if (or (is-eq owner tx-sender) (is-eq owner contract-caller))
(nft-burn? boom id owner)
(err u4))
(err u3)))
(define-read-only (get-owner (id uint))
(ok (nft-get-owner? boom id)))
(define-read-only (get-owner-raw? (id uint))
(nft-get-owner? boom id))
(define-read-only (get-boom-meta)
{uri: "https://boom.money/images/boom10.png", name: "Boom Collectible", mime-type: "image/png"}
)
(define-read-only (get-series-meta-raw? (series-id uint))
(map-get? series-meta series-id))
(define-read-only (get-meta? (id uint))
(match (map-get? meta id)
nft-meta
(let (
(series-id (get series-id nft-meta))
(number (get number nft-meta))
)
(match (map-get? series-meta series-id)
series
(some {
hash: (get hash series),
mime-type: (get mime-type series),
series-id: (get series-id nft-meta),
uri: (get uri series),
number: number
})
none))
none)
)
(define-read-only (get-meta-by-serial?
(series-id uint)
(number uint))
(match (map-get? index-by-series-item {series-id: series-id, number: number})
id
(match (map-get? meta id)
relation
(let ((series (unwrap-panic (map-get? series-meta (get series-id relation)))))
(some {
hash: (get hash series),
mime-type: (get mime-type series),
number: (get number relation),
series-id: series-id,
uri: (get uri series)
}))
none)
none))
(define-read-only (get-last-token-id)
(ok (var-get last-id)))
(define-read-only (get-last-token-id-raw)
(var-get last-id))
(define-read-only (last-token-id)
(ok (var-get last-id)))
(define-read-only (get-token-uri (nft-id uint))
(let (
(nft-series-id (get series-id (unwrap! (map-get? meta nft-id) (ok none))))
(series-meta-data (map-get? series-meta nft-series-id))
)
(ok (get uri series-meta-data))))
(define-read-only (last-token-id-raw)
(var-get last-id))
(define-read-only (last-series-id-raw)
(var-get last-series-id)
)
(define-private (asserts-panic (value bool))
(unwrap-panic (if value (some value) none))) | 0x91f5ca91f9ca038a0def4ad6a7b692c5e975f531be272b2e46854621174af7b9 | 13,316 | abort_by_response |
Zen | ;; mint fungible tokens via Dapparatus
;; with a fixed max supply and pass all to sender
(define-constant sender 'SP1TA84JTP4YRFWBK7PYKBA33H3YB60XP654RAR7M)
(define-fungible-token Zen u21000000)
(begin (ft-mint? Zen u21000000 sender)) | 0x619444409b8922d217f531b9db549dbbc675102a1dfb18af4e11af56e5cba33c | 13,374 | success |
Uru | ;; Mint Fungible Tokens via Dapparatus with max supply sent to sender
(define-constant sender 'SP1TA84JTP4YRFWBK7PYKBA33H3YB60XP654RAR7M)
(define-fungible-token Uru u21000000)
(ft-mint? Uru u21000000 sender)
;; traits of contract for function calls against it
(define-trait ft-trait
(
;; Transfer from caller to new principal
(transfer (uint principal principal) (repsponse bool uint))
;; Additonal Gets
(get-name () (response (string-ascii 32) uint))
(get-symbol () (response (string-ascii 32) uint))
(get-decimals () (response uint uint))
(get-balace-of (principal) (response uint uint))
(get-total-supply () (response uint uint))
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
) | 0xa4baf967aa18cb1f6844363a39bbc85acf3d65aa0fc9ff4cbcfb391f7df82aa5 | 13,411 | abort_by_response |
Uru | ;; Mint Fungible Tokens via Dapparatus with max supply sent to minter
(define-constant minter 'SP1TA84JTP4YRFWBK7PYKBA33H3YB60XP654RAR7M)
(define-fungible-token Uru u21000000)
(ft-mint? Uru u21000000 minter)
;; traits of contract for function calls against it
(define-trait ft-trait
(
;; Transfer from caller to new principal
(transfer (uint principal principal) (repsponse bool uint))
;; Additonal Gets
(get-name () (response (string-ascii 32) uint))
(get-symbol () (response (string-ascii 32) uint))
(get-decimals () (response uint uint))
(get-balance-of (principal) (response uint uint))
(get-total-supply () (response uint uint))
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
) | 0xbf05beedb8f0bbf08492db5960d73888f7c16749b9727728c4d9005cca91417c | 13,415 | abort_by_response |
Uru | ;; Mint Fungible Tokens via Dapparatus with max supply sent to minter
(define-constant minter 'SP1TA84JTP4YRFWBK7PYKBA33H3YB60XP654RAR7M)
(define-fungible-token Uru u21000000)
(ft-mint? Uru u21000000 minter)
;; traits of contract for function calls against it
(define-trait ft-trait
(
;; Transfer from caller to new principal
(transfer (uint principal principal) (response bool uint))
;; Additonal Gets
(get-name () (response (string-ascii 32) uint))
(get-symbol () (response (string-ascii 32) uint))
(get-decimals () (response uint uint))
(get-balance-of (principal) (response uint uint))
(get-total-supply () (response uint uint))
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
) | 0x4a81366ef6da2d7571aa9445a3c28c21cebf58a07effa5d7ef8ec18a8ca41d79 | 13,417 | success |
test1 | (define-non-fungible-token test1) | 0xc4cebe2d90f87afe502d154ad60237898a1339de389a886f5440a5700f944d9c | 13,457 | abort_by_response |
test1 | (nft-get-owner? test1 'sup' ) | 0x564968633a53da7cde7cbeee806a2c12890e36713815f56755dc5b51c966d65e | 13,460 | abort_by_response |
test1 | (define-non-fungible-token quartz (string-ascii 40))
(nft-mint? quartz "quick" "SPH30YCECRTRYW5NXQVFWR1FNTE02FZ3JZYP8GTD") | 0x91a219c27f8f30e7b4c13bcbe9bbebe058c35d8b43a281b757696d9a7e557ebe | 13,463 | abort_by_response |
Obelisk | ;; Mint Fungible Tokens via Dapparatus with max supply sent to minter
(define-constant ERR-UNAUTHORIZED u3)
(define-constant minter 'SP1TA84JTP4YRFWBK7PYKBA33H3YB60XP654RAR7M)
(define-fungible-token Obelisk u42000000)
(ft-mint? Obelisk u42000000 minter)
;; SIP-010 ;;
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard.ft-trait)
(define-public (transfer (amount uint) (from principal) (to principal))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(ft-transfer? Obelisk amount from to)
)
)
(define-public (get-name)
(ok "Obelisk"))
(define-public (get-symbol)
(ok "OBL"))
(define-public (get-decimals)
(ok u6))
(define-public (get-balance-of (user principal))
(ok (ft-get-balance Obelisk user)))
(define-public (get-total-supply)
(ok u42000000)
(define-public (get-token-uri)
(ok none)) | 0x966d70ee491c6576607b0ad6c5ea4f15aa822e98559eccd63587af2b6277b5b7 | 13,484 | abort_by_response |
Obelisk | ;; Mint Fungible Tokens via Dapparatus with max supply sent to minter
(define-constant ERR-UNAUTHORIZED u3)
(define-constant minter 'SP1TA84JTP4YRFWBK7PYKBA33H3YB60XP654RAR7M)
(define-fungible-token Obelisk u42000000)
(ft-mint? Obelisk u42000000 minter)
;; SIP-010 ;;
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard.ft-trait)
(define-public (transfer (amount uint) (from principal) (to principal))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(ft-transfer? Obelisk amount from to)
)
)
(define-public (get-name)
(ok "Obelisk"))
(define-public (get-symbol)
(ok "OBL"))
(define-public (get-decimals)
(ok u6))
(define-public (get-balance-of (user principal))
(ok (ft-get-balance Obelisk user)))
(define-public (get-total-supply)
(ok u42000000)
(define-public (get-token-uri)
(ok none)) | 0x966d70ee491c6576607b0ad6c5ea4f15aa822e98559eccd63587af2b6277b5b7 | 13,484 | abort_by_response |
Obelisk | ;; Mint Fungible Tokens via Dapparatus with max supply sent to minter
(define-constant ERR-UNAUTHORIZED u3)
(define-constant minter 'SP1TA84JTP4YRFWBK7PYKBA33H3YB60XP654RAR7M)
(define-fungible-token Obelisk u21000000)
(ft-mint? Obelisk u21000000 minter)
;; SIP-010 ;;
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard.ft-trait)
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(asserts! (is-eq from sender)
(err ERR-UNAUTHORIZED))
(ft-transfer? Obelisk amount sender recipient)
)
)
(define-public (get-name)
(ok "Obelisk"))
(define-public (get-symbol)
(ok "OBL"))
(define-public (get-decimals)
(ok u4))
(define-public (get-balance-of (user principal))
(ok (ft-get-balance Obelisk user)))
(define-public (get-total-supply)
(ok u21000000)
(define-public (get-token-uri)
(ok none)) | 0xff098ca30bba3f99c764411e02204e82061a26c8285b3a251493ce26309f10bc | 13,544 | abort_by_response |
Obelisk | ;; Mint Fungible Tokens via Dapparatus with max supply sent to minter
(define-constant minter 'SP1TA84JTP4YRFWBK7PYKBA33H3YB60XP654RAR7M)
(define-fungible-token Obelisk u42000000)
(ft-mint? Obelisk u42000000 minter)
(define-public (get-name)
(ok "Obelisk"))
(define-public (get-symbol)
(ok "OBL"))
(define-public (get-decimals)
(ok u4))
(define-public (get-balance-of (user principal))
(ok (ft-get-balance Obelisk user)))
(define-public (get-token-uri)
(ok none))
(define-public (transfer (to principal) (amount uint))
(if
(> (ft-get-balance Obelisk tx-sender) u0)
(ft-transfer? Obelisk amount tx-sender to)
(err u0))) | 0x5e7c2142b04f41fee10aeed68f8799f953166572e5b01a268177d188b32ae876 | 13,547 | success |
Hollow_Purple | (define-non-fungible-token Hollow_Purple 486f6c6c6f775f507572706c65) | 0x9fb2d05746bc32e1abd3d721212b2ad6fd24bf8e677ae0fde91a8a33d59edf42 | 13,596 | abort_by_response |
Test_for_fungible_token | (define-fungible-token test-for-fungible-token u100000) | 0xb6894d4c1da85d612a3089f7ffaaa0ca42b759db283c8d298cba2771ea0d5713 | 13,599 | success |
Test_for_fungible_token | (define-fungible-token test-for-fungible-token u100000) | 0xb6894d4c1da85d612a3089f7ffaaa0ca42b759db283c8d298cba2771ea0d5713 | 13,599 | success |
Test_for_fungible_token1 | (define-non-fungible-token test-for-fungible-token1 u100000) | 0x95ff844b361ec1ab2e34bedc97b8650f5d9fb628c24ed8f8cd63d61d5b6f0725 | 13,610 | abort_by_response |
Milky-Way | (define-fungible-token Milky-Way)
(define-data-var total-supply uint u0)
(define-read-only (get-total-supply)
(var-get total-supply))
(define-private (mint! (account principal) (amount uint))
(if (<= amount u0)
(err u0)
(begin
(var-set total-supply (+ (var-get total-supply) amount))
(ft-mint? Milky-Way amount account))))
(define-public (transfer (to principal) (amount uint))
(if
(> (ft-get-balance Milky-Way tx-sender) u0)
(ft-transfer? Milky-Way amount tx-sender to)
(err u0)))
(mint! 'SP1P72Z3704VMT3DMHPP2CB8TGQWGDBHD3RPR9GZS u60000000000000)
(mint! 'SP13VH72MJJAZGWVH8XBR8SBZ00S81A3ZWBR9DPDA u60000000000000)
| 0x7559b1e4e4b6dfc923d86ebc4ddf120f92fb0686afd0db7c1a4b8b70112efddb | 13,775 | success |
contract-20260699149 | ;; wrap the native STX token into an SRC20 compatible token to be usable along other tokens
;; Use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard)
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(begin
(ok (print (stx-get-balance owner)))))
(define-read-only (get-total-supply)
(ok stx-liquid-supply))
;; returns the token name
(define-read-only (get-name)
(ok "STX"))
(define-read-only (get-symbol)
(ok "STX"))
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6))
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/stx.json")))
;; {
;; "name":"STX",
;; "description":"STX token, as a SIP-010 compatible token",
;; "image":"https://swapr.finance/tokens/stx.png",
;; "vector":"https://swapr.finance/tokens/stx.svg"
;; }
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (> (get-balance-of sender) u0)
(begin
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(stx-transfer? amount tx-sender recipient))
(err u0))) | 0x465968b11249cbb7e4a53c10dd6a0a37a0efcc0aeeb68a5a8edd4956bea6f2d8 | 13,815 | abort_by_response |
contract-20260699149 | ;; wrap the native STX token into an SRC20 compatible token to be usable along other tokens
;; Use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard)
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(begin
(ok (print (stx-get-balance owner)))))
(define-read-only (get-total-supply)
(ok stx-liquid-supply))
;; returns the token name
(define-read-only (get-name)
(ok "STX"))
(define-read-only (get-symbol)
(ok "STX"))
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6))
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/stx.json")))
;; {
;; "name":"STX",
;; "description":"STX token, as a SIP-010 compatible token",
;; "image":"https://swapr.finance/tokens/stx.png",
;; "vector":"https://swapr.finance/tokens/stx.svg"
;; }
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (> (get-balance-of sender) u0)
(begin
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(stx-transfer? amount tx-sender recipient))
(err u0))) | 0x465968b11249cbb7e4a53c10dd6a0a37a0efcc0aeeb68a5a8edd4956bea6f2d8 | 13,815 | abort_by_response |
tk-stacks | ;; Wrap the native STX token into an SRC20 compatible token to be usable along other tokens
;; Use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard)
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(begin
(ok (print (stx-get-balance owner)))))
(define-read-only (get-total-supply)
(ok stx-liquid-supply))
;; returns the token name
(define-read-only (get-name)
(ok "STX"))
(define-read-only (get-symbol)
(ok "STX"))
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6))
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/stx.json")))
;; {
;; "name":"STX",
;; "description":"STX token, as a SIP-010 compatible token",
;; "image":"https://swapr.finance/tokens/stx.png",
;; "vector":"https://swapr.finance/tokens/stx.svg"
;; }
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (> (get-balance-of sender) u0)
(begin
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(stx-transfer? amount tx-sender recipient))
(err u0))) | 0x8bdd1817d7f8c9f7ccd76bbd588e96c2380573ea04913d1184df107b5a1a53d0 | 13,914 | abort_by_response |
tk-stacks | ;; Wrap the native STX token into an SRC20 compatible token to be usable along other tokens
;; Use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard)
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(begin
(ok (print (stx-get-balance owner)))))
(define-read-only (get-total-supply)
(ok stx-liquid-supply))
;; returns the token name
(define-read-only (get-name)
(ok "STX"))
(define-read-only (get-symbol)
(ok "STX"))
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6))
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/stx.json")))
;; {
;; "name":"STX",
;; "description":"STX token, as a SIP-010 compatible token",
;; "image":"https://swapr.finance/tokens/stx.png",
;; "vector":"https://swapr.finance/tokens/stx.svg"
;; }
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (> (get-balance-of sender) u0)
(begin
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(stx-transfer? amount tx-sender recipient))
(err u0))) | 0x8bdd1817d7f8c9f7ccd76bbd588e96c2380573ea04913d1184df107b5a1a53d0 | 13,914 | abort_by_response |
appmap-v1 | ;; application registry for applications wishing to sell NFTs throug the marketplace
(define-data-var administrator principal tx-sender)
;; (define-data-var administrator principal 'ST1NXBK3K5YYMD6FD41MVNP3JS1GABZ8TRVX023PT)
;; (define-data-var administrator principal 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ)
(define-map app-map {index: int} {owner: principal, app-contract-id: (buff 100), storage-model: int, status: int})
(define-map app-map-reverse {app-contract-id: (buff 100)} {index: int})
(define-data-var app-counter int 0)
(define-constant not-found (err u100))
(define-constant illegal-storage (err u102))
(define-constant not-allowed (err u101))
;; -- writers --
(define-public (transfer-administrator (new-administrator principal))
(begin
(asserts! (is-eq (var-get administrator) contract-caller) not-allowed)
(var-set administrator new-administrator)
(ok true)))
;; Insert new app at current index - can't have two apps with the same contract id here!
(define-public (register-app (owner principal) (app-contract-id (buff 100)) (storage-model int))
(let
(
(appIndex (get index (map-get? app-map-reverse {app-contract-id: app-contract-id})))
)
(if (is-none appIndex)
(begin
(if (is-storage-allowed storage-model)
(begin
(map-insert app-map {index: (var-get app-counter)} {owner: owner, app-contract-id: app-contract-id, storage-model: storage-model, status: 0})
(map-insert app-map-reverse {app-contract-id: app-contract-id} {index: (var-get app-counter)})
(var-set app-counter (+ (var-get app-counter) 1))
(print (var-get app-counter))
(ok (var-get app-counter))
)
illegal-storage
)
)
not-allowed
)
)
)
(define-public (update-app (index int) (owner principal) (app-contract-id (buff 100)) (storage-model int) (status int))
(begin
(asserts! (is-ok (is-update-allowed index)) not-allowed)
(ok (map-set app-map {index: index} {owner: owner, app-contract-id: app-contract-id, storage-model: storage-model, status: status}))
)
)
;; Make app live - set status to 1
(define-public (set-app-status (index int) (status int))
(let
(
(owner (unwrap! (get owner (map-get? app-map {index: index})) not-allowed))
(app-contract-id (unwrap! (get app-contract-id (map-get? app-map {index: index})) not-allowed))
(storage-model (unwrap! (get storage-model (map-get? app-map {index: index})) not-allowed))
)
(asserts! (is-ok (is-update-allowed index)) not-allowed)
(ok (map-set app-map {index: index} {owner: owner, app-contract-id: app-contract-id, storage-model: storage-model, status: status}))
)
)
;; -- read only --
;; Get app by index
(define-read-only (get-app (index int))
(match (map-get? app-map {index: index})
myProject (ok myProject) not-found
)
)
(define-read-only (get-app-index (app-contract-id (buff 100)))
(let
(
(index (unwrap! (get index (map-get? app-map-reverse {app-contract-id: app-contract-id})) not-found))
)
(ok index)
)
)
(define-read-only (get-app-counter)
(ok (var-get app-counter))
)
;; Get current administrator
(define-read-only (get-administrator)
(ok (var-get administrator))
)
(define-read-only (get-contract-data)
(let
(
(the-app-counter (var-get app-counter))
(the-administrator (var-get administrator))
)
(ok (tuple
(appCounter the-app-counter)
(administrator the-administrator)
)
)
)
)
;; -- private --
(define-private (is-update-allowed (index int))
(let
(
(owner (unwrap! (get owner (map-get? app-map {index: index})) not-allowed))
)
(if (or (is-eq (var-get administrator) contract-caller) (is-eq owner contract-caller))
(ok true)
not-allowed
)
)
)
(define-private (is-storage-allowed (storage int))
(<= storage 10)
) | 0x7ff5f3204bc38ceca15058dc1f4c515beacd33a10b5a9e438c2da67ca38d85c2 | 14,481 | success |
thisisnumberone-v1 |
;; Interface definitions
;; (impl-trait 'ST1ESYCGJB5Z5NBHS39XPC70PGC14WAQK5XXNQYDW.nft-interface.transferable-nft-trait)
;; (impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-interface.tradable-nft-trait)
(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
;; contract variables
(define-data-var administrator principal 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ)
(define-data-var mint-price uint u100000)
(define-data-var base-token-uri (string-ascii 256) "https://thisisnumberone.com/mesh/v2/asset/")
(define-data-var mint-counter uint u0)
(define-data-var platform-fee uint u5)
;; constants
(define-constant token-name "thisisnumberone-v1")
(define-constant token-symbol "#1")
;; Non Fungible Token, modeled after ERC-721 via nft-trait
;; Note this is a basic implementation - no support yet for setting approvals for assets
;; NFT are identified by nft-index (uint) which is tied via a reverse lookup to a real world
;; asset hash - SHA 256 32 byte value. The Asset Hash is used to tie arbitrary real world
;; data to the NFT
(define-non-fungible-token my-nft uint)
;; data structures
(define-map nft-lookup {asset-hash: (buff 32), edition: uint} {nft-index: uint})
(define-map nft-data {nft-index: uint} {asset-hash: (buff 32), meta-data-url: (buff 200), max-editions: uint, edition: uint, edition-cost: uint, mint-block-height: uint, series-original: uint})
(define-map nft-sale-data {nft-index: uint} {sale-type: uint, increment-stx: uint, reserve-stx: uint, amount-stx: uint, bidding-end-time: uint, sale-cycle-index: uint})
(define-map nft-beneficiaries {nft-index: uint} { addresses: (list 10 principal), shares: (list 10 uint) })
(define-map nft-bid-history {nft-index: uint, bid-index: uint} {sale-cycle: uint, bidder: principal, amount: uint, app-timestamp: uint})
(define-map nft-offer-history {nft-index: uint, offer-index: uint} {sale-cycle: uint, offerer: principal, app-timestamp: uint, amount: uint, accepted: uint})
;; counters keep track per NFT of the...
;; a) number of editions minted (1 based index)
;; b) number of offers made (0 based index)
;; c) number of bids made (0 based index)
(define-map nft-offer-counter {nft-index: uint} {offer-counter: uint, sale-cycle: uint})
(define-map nft-edition-counter {nft-index: uint} {edition-counter: uint})
(define-map nft-high-bid-counter {nft-index: uint} {high-bid-counter: uint, sale-cycle: uint})
(define-constant percentage-with-twodp u10000000000)
;; (define-constant percentage-with-twodp u10000)
(define-constant not-allowed (err u10))
(define-constant not-found (err u11))
(define-constant amount-not-set (err u12))
(define-constant seller-not-found (err u13))
(define-constant asset-not-registered (err u14))
(define-constant transfer-error (err u15))
(define-constant not-approved-to-sell (err u16))
(define-constant same-spender-err (err u17))
(define-constant failed-to-mint-err (err u18))
(define-constant edition-counter-error (err u19))
(define-constant edition-limit-reached (err u20))
(define-constant user-amount-different (err u21))
(define-constant failed-to-stx-transfer (err u22))
(define-constant failed-to-close-1 (err u23))
(define-constant failed-to-close-2 (err u24))
(define-constant failed-to-close-3 (err u24))
(define-constant cant-pay-mint-price (err u25))
(define-constant editions-error (err u26))
(define-constant payment-error (err u28))
(define-constant payment-address-error (err u33))
(define-constant payment-share-error (err u34))
(define-constant bidding-error (err u35))
(define-constant prevbid-bidding-error (err u36))
(define-constant not-originale (err u37))
(define-constant bidding-opening-error (err u38))
(define-constant bidding-amount-error (err u39))
(define-constant bidding-endtime-error (err u40))
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-constant nft-not-found-err (err u404)) ;; not found
;; interface methods
;; from nft-trait: Last token ID, limited to uint range
;; note decrement as mint counter is the id of the next nft
(define-read-only (get-last-token-id)
(ok (- (var-get mint-counter) u1))
)
;; from nft-trait: URI for metadata associated with the token
(define-read-only (get-token-uri (nftIndex uint))
(ok (some (var-get base-token-uri)))
)
;; from nft-trait: Gets the owner of the 'SPecified token ID.
(define-read-only (get-owner (nftIndex uint))
(ok (nft-get-owner? my-nft nftIndex))
)
;; Transfers tokens to a 'SPecified principal.
(define-public (transfer (nftIndex uint) (owner principal) (recipient principal))
(if (and (is-owner nftIndex owner) (is-eq owner tx-sender))
(match (nft-transfer? my-nft nftIndex owner recipient)
success (ok true)
error (nft-transfer-err error))
nft-not-owned-err)
)
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; public methods
;; --------------
;; the contract administrator can change the contract administrator
(define-public (transfer-administrator (new-administrator principal))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set administrator new-administrator)
(ok true)
)
)
;; the contract administrator can change the transfer fee charged by the contract on sale of tokens
(define-public (change-fee (new-fee uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set platform-fee new-fee)
(ok true)
)
)
;; the contract administrator can change the base uri - where meta data for tokens in this contract
;; are located
(define-public (update-base-token-uri (new-base-token-uri (string-ascii 256)))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set base-token-uri new-base-token-uri)
(ok true)
)
)
;; the contract administrator can change the mint price
(define-public (update-mint-price (new-mint-price uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set mint-price new-mint-price)
(ok true)
)
)
;; The administrator can transfer the balance in the contract to another address
(define-public (transfer-balance (recipient principal))
(let
(
(balance (stx-get-balance (as-contract tx-sender)))
)
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(unwrap! (stx-transfer? balance (as-contract tx-sender) recipient) failed-to-stx-transfer)
(print "refund-bid : refunded bid to biddder")
(ok balance)
)
)
;; adds an offer to the list of offers on an NFT
(define-public (make-offer (nft-index uint) (amount uint) (app-timestamp uint))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerCounter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nft-index}))))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nft-index})) amount-not-set))
)
(asserts! (is-eq saleType u3) not-allowed)
(map-insert nft-offer-history {nft-index: nft-index, offer-index: offerCounter} {sale-cycle: saleCycleIndex, offerer: tx-sender, app-timestamp: app-timestamp, amount: amount, accepted: u0})
(map-set nft-offer-counter {nft-index: nft-index} {sale-cycle: saleCycleIndex, offer-counter: (+ offerCounter u1)})
(ok (+ offerCounter u1))
)
)
;; accept-offer
;; marks offer as accepted and transfers ownership to the recipient
(define-public (accept-offer (nft-index uint) (offer-index uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerer (unwrap! (get offerer (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(app-timestamp (unwrap! (get app-timestamp (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(sale-cycle (unwrap! (get sale-cycle (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(amount (unwrap! (get amount (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
)
(asserts! (is-eq saleType u3) not-allowed)
(map-set nft-offer-history {nft-index: nft-index, offer-index: offer-index} {sale-cycle: sale-cycle, offerer: offerer, app-timestamp: app-timestamp, amount: amount, accepted: u1})
(ok (transfer nft-index owner recipient))
)
)
;; mint a new token
;; asset-hash: sha256 hash of asset file
;; max-editions: maximum number of editions allowed for this asset
;; royalties: a list of priciple/percentages to be be paid from sale price
;;
;; 1. transfer mint price to the administrator
;; 2. mint the token using built in mint function
;; 3. update the two maps - first contains the data indexed by the nft index, second
;; provides a reverse lookup based on the asset hash - this allows tokens to be located
;; from just a knowledge of the original asset.
;; Note series-original in the case of the original in series is just
;; mintCounter - for editions this provides a safety hook back to the original in cases
;; where the asset hash is unknown (ie cant be found from nft-lookup).
(define-public (mint-token (asset-hash (buff 32)) (metaDataUrl (buff 200)) (maxEditions uint) (editionCost uint) (addresses (list 10 principal)) (shares (list 10 uint)))
(let
(
(mintCounter (var-get mint-counter))
(ahash (get asset-hash (map-get? nft-data {nft-index: (var-get mint-counter)})))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
)
(asserts! (> maxEditions u0) editions-error)
(asserts! (> (stx-get-balance tx-sender) (var-get mint-price)) cant-pay-mint-price)
(asserts! (is-none ahash) asset-not-registered)
;; Note: series original is really for later editions to refer back to this one - this one IS the series original
(map-insert nft-data {nft-index: mintCounter} {asset-hash: asset-hash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: u1, edition-cost: editionCost, mint-block-height: block-height, series-original: mintCounter})
;; Note editions are 1 based and <= maxEditions - the one minted here is #1
(map-insert nft-edition-counter {nft-index: mintCounter} {edition-counter: u2})
;; By default we accept offers - sale type can be changed via the UI.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(map-insert nft-lookup {asset-hash: asset-hash, edition: u1} {nft-index: mintCounter})
;; The payment is split between the nft-beneficiaries with share > 0 they are set per edition
(map-insert nft-beneficiaries {nft-index: mintCounter} {addresses: addresses, shares: shares})
;; finally - mint the NFT and step the counter
(if (is-eq tx-sender (var-get administrator))
(print "mint-token : tx-sender is contract - skipping mint price")
(begin
(unwrap! (stx-transfer? (var-get mint-price) tx-sender (var-get administrator)) failed-to-stx-transfer)
(print "mint-token : tx-sender paid mint price")
)
)
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
(print {evt: "mint-token", nftIndex: mintCounter, owner: tx-sender, amount: (var-get mint-price)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
(define-public (mint-edition (nftIndex uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(maxEditions (unwrap! (get max-editions (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCost (unwrap! (get edition-cost (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCounter (unwrap! (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex})) edition-counter-error))
(thisEdition (default-to u0 (get nft-index (map-get? nft-lookup {asset-hash: ahash, edition: editionCounter}))))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
(mintCounter (var-get mint-counter))
)
;; can only mint an edition via buy now or bidding - not offers
(asserts! (is-eq thisEdition u0) edition-counter-error)
;; Note - the edition index is 1 based and incremented before insertion in this method - therefore the test is '<=' here!
(asserts! (<= editionCounter maxEditions) edition-limit-reached)
;; This asserts the first one has been minted already - see mint-token.
(asserts! (> editionCounter u1) edition-counter-error)
;; check the buyer has enough funds..
(asserts! (> (stx-get-balance tx-sender) editionCost) cant-pay-mint-price)
;; set max editions so we know where we are in the series
(map-insert nft-data {nft-index: mintCounter} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: editionCounter, edition-cost: editionCost, mint-block-height: block-height, series-original: nftIndex})
;; put the nft index into the list of editions in the look up map
(map-insert nft-lookup {asset-hash: ahash, edition: editionCounter} {nft-index: mintCounter})
;; mint the NFT and update the counter for the next..
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
;; saleType = 1 (buy now) - split out the payments according to royalties - or roll everything back.
(if (> editionCost u0)
(begin (unwrap! (payment-split nftIndex editionCost tx-sender) failed-to-mint-err) (print "mint-edition : payment split made"))
(print "mint-edition : payment not required")
)
;; (print "mint-edition : payment managed")
;; initialise the sale data - not for sale until the owner sets it.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(print {evt: "mint-edition", nftIndex: nftIndex, owner: tx-sender, edition: editionCounter, amount: editionCost})
;; inncrement the mint counter and edition counter ready for the next edition
(map-set nft-edition-counter {nft-index: nftIndex} {edition-counter: (+ u1 editionCounter)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
;; allow the owner of the series original to set the cost of minting editions
;; the cost for each edition is taken from the series original and so we need to
;; operate on the the original here - ie nftIndex is the index of thee original
;; and NOT the edition andd only the creator of the series original can change this.
(define-public (set-edition-cost (nftIndex uint) (maxEditions uint) (editionCost uint))
(let
(
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(edition (unwrap! (get edition (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(mintBlockHeight (unwrap! (get mint-block-height (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(seriesOriginal (unwrap! (get series-original (map-get? nft-data {nft-index: nftIndex})) not-allowed))
)
(asserts! (is-owner nftIndex tx-sender) nft-not-owned-err)
(asserts! (is-eq nftIndex seriesOriginal) not-originale)
(ok (map-set nft-data {nft-index: nftIndex} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: edition, edition-cost: editionCost, mint-block-height: mintBlockHeight, series-original: seriesOriginal}))
)
)
;; set-sale-data updates the sale type and purchase info for a given NFT. Only the owner can call this method
;; and doing so make the asset transferable by the recipient - on condition of meeting the conditions of sale
;; This is equivalent to the setApprovalForAll method in ERC 721 contracts.
;; Assumption being made here is that all editions have the same sale data associated
(define-public (set-sale-data (nftIndex uint) (sale-type uint) (increment-stx uint) (reserve-stx uint) (amount-stx uint) (bidding-end-time uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
)
(asserts! (not (is-eq saleType u2)) bidding-error)
(print {evt: "set-sale-data", nftIndex: nftIndex, saleType: sale-type, increment: increment-stx, reserve: reserve-stx, amount: amount-stx, biddingEndTime: bidding-end-time})
(if (is-owner nftIndex tx-sender)
;; Note - don't override the sale cyle index here as this is a public method and can be called ad hoc. Sale cycle is update at end of sale!
(if (map-set nft-sale-data {nft-index: nftIndex} {sale-cycle-index: saleCycleIndex, sale-type: sale-type, increment-stx: increment-stx, reserve-stx: reserve-stx, amount-stx: amount-stx, bidding-end-time: bidding-end-time})
(ok nftIndex) not-allowed
)
not-allowed
)
)
)
;; buy-now
;; pay royalties and transfer asset ownership to tx-sender.
;; Checks that:
;; a) asset is registered
;; b) on sale via buy now
;; c) amount is set
;;
(define-public (buy-now (nftIndex uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(ahash (get asset-hash (map-get? nft-data {nft-index: nftIndex})))
)
(asserts! (is-some ahash) asset-not-registered)
(asserts! (is-eq saleType u1) not-approved-to-sell)
(asserts! (> amount u0) amount-not-set)
;; Make the royalty payments - then zero out the sale data and register the transfer
;; (print "buy-now : Make the royalty payments")
(print (unwrap! (payment-split nftIndex amount tx-sender) payment-error))
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
;; (print "buy-now : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(print {evt: "buy-now", nftIndex: nftIndex, owner: owner, recipient: recipient, amount: amount})
(nft-transfer? my-nft nftIndex owner recipient)
)
)
;; opening-bid
;; nft-index: unique index for NFT
;; The opening bid in the given sale cycle a given item.
(define-public (opening-bid (nftIndex uint) (bidAmount uint) (appTimestamp uint))
(let
(
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(biddingEndTime (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(bidCounter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(asserts! (is-eq bidCounter u0) bidding-opening-error)
(asserts! (is-eq bidAmount amount) bidding-amount-error)
(asserts! (> biddingEndTime appTimestamp) bidding-endtime-error)
(print "place-bid : sending this much to; ")
(print bidAmount)
(print (as-contract tx-sender))
(print "place-bid : when")
(print appTimestamp)
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: u0} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: u1, sale-cycle: saleCycle})
(print {evt: "opening-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: bidAmount})
(ok bidAmount)
)
)
(define-private (get-current-bidder (nftIndex uint) (currentBidIndex uint))
(let
(
(currentBidder (unwrap! (get bidder (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)})) bidding-error))
)
(ok currentBidder)
)
)
(define-private (get-current-bid-amount (nftIndex uint) (currentBidIndex uint))
(let
(
(currentAmount (unwrap! (get amount (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)})) bidding-error))
)
(ok currentAmount)
)
)
;; place-bid
;; nft-index: unique index for NFT
;; nextBidAmount: amount the user is bidding - i.e the amount display on th place bid button.
(define-public (place-bid (nftIndex uint) (nextBidAmount uint) (appTimestamp uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amountStart (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(increment (unwrap! (get increment-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(reserve (unwrap! (get reserve-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(currentBidIndex (unwrap! (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex})) not-allowed))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
(owner (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(print "place-bid : assert there is an opening bid - otherwise client calls opening-bid")
(print currentAmount)
(asserts! (> currentAmount u0) user-amount-different)
(asserts! (is-eq nextBidAmount (+ currentAmount increment)) user-amount-different)
;; if (appTimestamp > bidding-end-time) then this is either the winning or a too late bid on the NFT
;; a too late bid will have been rejected as the last bid resets the sale/bidding data on the item.
;; if its the last bid...
;; 1. Refund the currentBid to the bidder
;; 2. move currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
;; (next-bid) we
;; 1. Refund the currentBid to the bidder
;; 2. Insert currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
(print "place-bid : currentBidIndex")
(print currentBidIndex)
(print "place-bid : bidding-end-time")
(print bidding-end-time)
(print "place-bid : appTimestamp")
(print appTimestamp)
(print "place-bid : reserve")
(print reserve)
(if (> appTimestamp bidding-end-time)
(begin
(print "place-bid : bid is after end time refund current bid")
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-stx-transfer)
(if (< nextBidAmount reserve)
;; if this bid is less than reserve & its the last bid then just refund previous bid
(unwrap! (ok true) failed-to-stx-transfer)
(begin
;; WINNING BID - is the FIRST bid after bidding close.
(print "place-bid : Make the royalty payments")
(unwrap! (payment-split nftIndex nextBidAmount tx-sender) payment-error)
(unwrap! (record-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycle u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(print "place-bid : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(unwrap! (nft-transfer? my-nft nftIndex owner tx-sender) failed-to-stx-transfer)
)
)
)
(begin
(print "place-bid : bid is before end time refund current bid from the contract")
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-stx-transfer)
(print "place-bid : and transfer this bid into the contract")
(unwrap! (next-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
)
)
;;
;; NOTE: Above code will only reconcile IF a bid comes in after 'block-time'
;; We may need a manual trigger to end bidding when this doesn't happen - unless there is a
;; to repond to future events / timeouts that I dont know about.
;;
(print {evt: "place-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: nextBidAmount})
(ok true)
)
)
;; Mint subsequent editions of the NFT
;; nft-index: the index of the original NFT in this series of editions.
;; The sale data must have been set on the asset before calling this.
;; The amount is split according to the royalties.
;; The nextBidAmount is passed to avoid concurrency issues - amount on the buy/bid button must
;; equal the amount expected by the contract.
;; close-bidding
;; nft-index: index of the NFT
;; closeType: type of closure, values are;
;; 1 = buy now closure - uses the last bid (thats held in escrow) to transfer the item to the bidder and to pay royalties
;; 2 = refund closure - the last bid gets refunded and sale is closed. The item ownership does not change.
;; Note bidding can also be closed automatically - if a bid is received after the bidding end time.
;; In the context of a 'live auction' items have no end time and are closed by the 'auctioneer'.
(define-public (close-bidding (nftIndex uint) (closeType uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) failed-to-close-1))
(block-time (unwrap! (get-block-info? time u0) not-allowed))
(currentBidIndex (unwrap! (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex})) not-allowed))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
)
(asserts! (or (is-eq closeType u1) (is-eq closeType u2)) failed-to-close-1)
;; only the owner or administrator can call close
(asserts! (or (is-owner nftIndex tx-sender) (unwrap! (is-administrator) failed-to-close-2)) failed-to-close-2)
;; only the administrator can call close BEFORE the end time - note we use the less accurate
;; but fool proof block time here to prevent owner/client code jerry mandering the close function
(asserts! (or (> block-time bidding-end-time) (unwrap! (is-administrator) failed-to-close-3)) failed-to-close-3)
;; Check for a current bid - if none then just reset the sale data to not selling
(if (is-eq currentAmount u0)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(if (is-eq closeType u1)
(begin
;; buy now closure - pay and transfer ownership
;; note that the money to pay with is in the contract!
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "from-contract", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount, currentBidIndex: currentBidIndex})
(unwrap! (payment-split nftIndex currentAmount (as-contract tx-sender)) payment-error)
(unwrap! (nft-transfer? my-nft nftIndex (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err) tx-sender) failed-to-close-2)
)
(begin
;; refund closure - refund the bid and reset sale data
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "refund", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-close-2)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
)
)
)
(print {evt: "close-bidding", nftIndex: nftIndex, closeType: closeType, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok nftIndex)
)
)
;; read only methods
;; ---------------
(define-read-only (get-administrator)
(var-get administrator))
(define-read-only (is-administrator)
(ok (is-eq (var-get administrator) tx-sender)))
(define-read-only (get-base-token-uri)
(var-get base-token-uri))
(define-read-only (get-mint-counter)
(ok (var-get mint-counter))
)
(define-read-only (get-mint-price)
(var-get mint-price))
(define-read-only (get-token-by-index (nftIndex uint))
(ok (get-all-data nftIndex))
)
(define-read-only (get-beneficiaries (nftIndex uint))
(let
(
(beneficiaries (map-get? nft-beneficiaries {nft-index: nftIndex}))
)
(ok beneficiaries)
)
)
(define-read-only (get-offer-at-index (nftIndex uint) (offerIndex uint))
(let
(
(the-offer (map-get? nft-offer-history {nft-index: nftIndex, offer-index: offerIndex}))
)
(ok the-offer)
)
)
(define-read-only (get-bid-at-index (nftIndex uint) (bidIndex uint))
(let
(
(the-bid (map-get? nft-bid-history {nft-index: nftIndex, bid-index: bidIndex}))
)
(ok the-bid)
)
)
;; Get the edition from a knowledge of the #1 edition and the specific edition number
(define-read-only (get-edition-by-hash (asset-hash (buff 32)) (edition uint))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: edition})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-token-by-hash (asset-hash (buff 32)))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: u1})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-contract-data)
(let
(
(the-administrator (var-get administrator))
(the-mint-price (var-get mint-price))
(the-base-token-uri (var-get base-token-uri))
(the-mint-counter (var-get mint-counter))
(the-platform-fee (var-get platform-fee))
(the-token-name token-name)
(the-token-symbol token-symbol)
)
(ok (tuple (administrator the-administrator)
(mintPrice the-mint-price)
(baseTokenUri the-base-token-uri)
(mintCounter the-mint-counter)
(platformFee the-platform-fee)
(tokenName the-token-name)
(tokenSymbol the-token-symbol)))
)
)
(define-private (get-all-data (nftIndex uint))
(let
(
(the-owner (unwrap-panic (nft-get-owner? my-nft nftIndex)))
(the-token-info (map-get? nft-data {nft-index: nftIndex}))
(the-sale-data (map-get? nft-sale-data {nft-index: nftIndex}))
(the-beneficiary-data (map-get? nft-beneficiaries {nft-index: nftIndex}))
(the-edition-counter (default-to u0 (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex}))))
(the-offer-counter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nftIndex}))))
(the-high-bid-counter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
(ok (tuple (offerCounter the-offer-counter)
(bidCounter the-high-bid-counter)
(editionCounter the-edition-counter)
(nftIndex nftIndex)
(tokenInfo the-token-info)
(saleData the-sale-data)
(beneficiaryData the-beneficiary-data)
(owner the-owner)
)
)
)
)
(define-read-only (get-sale-data (nftIndex uint))
(match (map-get? nft-sale-data {nft-index: nftIndex})
mySaleData
(ok mySaleData)
not-found
)
)
(define-read-only (get-token-name)
(ok token-name)
)
(define-read-only (get-token-symbol)
(ok token-symbol)
)
(define-read-only (get-balance)
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(ok (stx-get-balance (as-contract tx-sender)))
)
)
;; private methods
;; ---------------
(define-private (refund-bid (nftIndex uint) (currentBidder principal) (currentAmount uint))
(begin
(unwrap! (as-contract (stx-transfer? currentAmount tx-sender currentBidder)) failed-to-stx-transfer)
(print {evt: "refund-bid", nftIndex: nftIndex, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok true)
)
)
;; need to account for reserve-stx
(define-private (record-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
;; see place-bid for the payment - no need for this (unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {evt: "record-bid", nftIndex: nftIndex, txSender: tx-sender, bidAmount: bidAmount, bidCounter: bidCounter, appTimestamp: appTimestamp, saleCycle: saleCycle})
(ok true)
)
)
(define-private (next-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {appTimestamp: appTimestamp, bidAmount: bidAmount, bidCounter: bidCounter, evt: "next-bid", nftIndex: nftIndex, saleCycle: saleCycle, txSender: tx-sender})
(ok true)
)
)
;; sends payments to each recipient listed in the royalties
;; Note this is called by mint-edition where thee nftIndex actuallt referes to the series orginal and is where the royalties are stored.
(define-private (payment-split (nftIndex uint) (saleAmount uint) (payer principal))
(let
(
(addresses (unwrap! (get addresses (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(shares (unwrap! (get shares (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(split u0)
)
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u0) payment-address-error) (unwrap! (element-at shares u0) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u1) payment-address-error) (unwrap! (element-at shares u1) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u2) payment-address-error) (unwrap! (element-at shares u2) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u3) payment-address-error) (unwrap! (element-at shares u3) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u4) payment-address-error) (unwrap! (element-at shares u4) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u5) payment-address-error) (unwrap! (element-at shares u5) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u6) payment-address-error) (unwrap! (element-at shares u6) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u7) payment-address-error) (unwrap! (element-at shares u7) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u8) payment-address-error) (unwrap! (element-at shares u8) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u9) payment-address-error) (unwrap! (element-at shares u9) payment-share-error)) payment-share-error))
(print {evt: "payment-split", nftIndex: nftIndex, payer: payer, saleAmount: saleAmount, txSender: tx-sender})
(print split)
(ok split)
)
)
;; In the pay-royalty function, the unit of saleAmount is in Satoshi and the share variable is a percentage (ex for 5% it will be equal to 5)
(define-private (pay-royalty (payer principal) (saleAmount uint) (payee principal) (share uint))
(begin
(if (> share u0)
(let
(
(split (/ (* saleAmount share) percentage-with-twodp))
)
;; ignore royalty payment if its to the buyer / tx-sender.
(if (not (is-eq tx-sender payee))
(unwrap! (stx-transfer? split payer payee) transfer-error)
(unwrap! (ok true) transfer-error)
)
(print {evt: "pay-royalty", payee: payee, payer: payer, saleAmount: saleAmount, share: share, txSender: tx-sender})
(ok split)
)
(ok u0)
)
)
)
(define-private (is-owner (nft-index uint) (user principal))
(is-eq user
;; if no owner, return false
(unwrap! (nft-get-owner? my-nft nft-index) false))
)
| 0xb8ae1c6f6f9de43bbeda0672b9b97a11d06212fbec40c5a65e4941d7a1df1812 | 14,484 | success |
XXXtentacion | (impl-trait 'SPHSC0CQC585RT86XBVYRBJ0HQC44VGQ83DH3AM8.nft-trait.nft-trait)
(define-non-fungible-token XXXtentacion uint)
;; Public functions
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant nft-not-found-err (err u404)) ;; not found
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; Transfers tokens to a specified principal.
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and
(is-eq tx-sender (unwrap! (nft-get-owner? XXXtentacion token-id) nft-not-found-err))
(is-eq tx-sender sender)
(not (is-eq recipient sender)))
(match (nft-transfer? XXXtentacionple token-id sender recipient)
success (ok success)
error (nft-transfer-err error))
nft-not-owned-err))
;; Gets the owner of the specified token ID.
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? XXXtentacion token-id)))
;; Gets the owner of the specified token ID.
(define-read-only (get-last-token-id)
(ok u1))
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/i%20spoke%20to%20the%20devil%20in%20miami.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T170143Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=9ce7d555e98047c4b1fc12d5b9a87037588c5e197074a1d5317eb9364ad61bfe")))
(define-read-only (get-meta (token-id uint))
(if (is-eq token-id u1)
(ok (some {name: "XXXtentacion", uri: "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/i%20spoke%20to%20the%20devil%20in%20miami.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T170143Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=9ce7d555e98047c4b1fc12d5b9a87037588c5e197074a1d5317eb9364ad61bfe", mime-type: "image/jpeg"}))
(ok none)))
(define-read-only (get-nft-meta)
(ok (some {name: "XXXtentacion", uri: "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/i%20spoke%20to%20the%20devil%20in%20miami.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T170143Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=9ce7d555e98047c4b1fc12d5b9a87037588c5e197074a1d5317eb9364ad61bfe", mime-type: "image/jpeg"})))
(define-read-only (get-errstr (code uint))
(ok (if (is-eq u401 code)
"nft-not-owned"
(if (is-eq u404 code)
"nft-not-found"
(if (is-eq u405 code)
"sender-equals-recipient"
"unknown-error")))))
;; Initialize the contract
(try! (nft-mint? XXXtentacion u1 tx-sender)) | 0xc6095acb4c01cdf03850e6fcfb16c2a261dd6f3d37cfa74feca08d315c7c96b1 | 14,692 | abort_by_response |
XXXtentacion | (impl-trait 'SPHSC0CQC585RT86XBVYRBJ0HQC44VGQ83DH3AM8.nft-trait.nft-trait)
(define-non-fungible-token XXXtentation #1 uint)
;; Public functions
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant nft-not-found-err (err u404)) ;; not found
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; Transfers tokens to a specified principal.
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and
(is-eq tx-sender (unwrap! (nft-get-owner? t token-id) nft-not-found-err))
(is-eq tx-sender sender)
(not (is-eq recipient sender)))
(match (nft-transfer? t token-id sender recipient)
success (ok success)
error (nft-transfer-err error))
nft-not-owned-err))
;; Gets the owner of the specified token ID.
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? XXXtentation #1 token-id)))
;; Gets the owner of the specified token ID.
(define-read-only (get-last-token-id)
(ok u1))
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae")))
(define-read-only (get-meta (token-id uint))
(if (is-eq token-id u1)
(ok (some {name: "XXXtentation #1", uri: "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae", mime-type: "song/mp4"}))
(ok none)))
(define-read-only (get-nft-meta)
(ok (some {name: "tXXXtentation #1", uri: "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae", mime-type: "song/mp4"})))
(define-read-only (get-errstr (code uint))
(ok (if (is-eq u401 code)
"nft-not-owned"
(if (is-eq u404 code)
"nft-not-found"
(if (is-eq u405 code)
"sender-equals-recipient"
"unknown-error")))))
;; Initialize the contract
(try! (nft-mint? XXXtentation #1 u1 tx-sender)) | 0x9c161a788bf195043fe20d7568167e2790332644ad83c88bc4ce636ffed9aeb3 | 14,694 | abort_by_response |
XXXtentation | (impl-trait 'SP13VH72MJJAZGWVH8XBR8SBZ00S81A3ZWBR9DPDA.nft-trait.nft-trait)
(define-non-fungible-token XXXtentation uint)
;; Public functions
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant nft-not-found-err (err u404)) ;; not found
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; Transfers tokens to a specified principal.
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and
(is-eq tx-sender (unwrap! (nft-get-owner? XXXtentation token-id) nft-not-found-err))
(is-eq tx-sender sender)
(not (is-eq recipient sender)))
(match (nft-transfer? XXXtentation token-id sender recipient)
success (ok success)
error (nft-transfer-err error))
nft-not-owned-err))
;; Gets the owner of the specified token ID.
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? XXXtentation token-id)))
;; Gets the owner of the specified token ID.
(define-read-only (get-last-token-id)
(ok u1))
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae")))
(define-read-only (get-meta (token-id uint))
(if (is-eq token-id u1)
(ok (some {name: "XXXtentation #1", uri: "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae", mime-type: "song/mp4"}))
(ok none)))
(define-read-only (get-nft-meta)
(ok (some {name: "tXXXtentation", uri: "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae", mime-type: "song/mp4"})))
(define-read-only (get-errstr (code uint))
(ok (if (is-eq u401 code)
"nft-not-owned"
(if (is-eq u404 code)
"nft-not-found"
(if (is-eq u405 code)
"sender-equals-recipient"
"unknown-error")))))
;; Initialize the contract
(try! (nft-mint? XXXtentation u1 tx-sender)) | 0xc18e602dcf6214a37d2cde5d9a3e8d0a7946bc8d4f0edabb86eaf0d7b4682975 | 14,698 | abort_by_response |
XXXtentation | (impl-trait 'SP13VH72MJJAZGWVH8XBR8SBZ00S81A3ZWBR9DPDA.nft-trait.nft-trait)
(define-non-fungible-token XXXtentation uint)
;; Public functions
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant nft-not-found-err (err u404)) ;; not found
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; Transfers tokens to a specified principal.
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and
(is-eq tx-sender (unwrap! (nft-get-owner? XXXtentation token-id) nft-not-found-err))
(is-eq tx-sender sender)
(not (is-eq recipient sender)))
(match (nft-transfer? XXXtentation token-id sender recipient)
success (ok success)
error (nft-transfer-err error))
nft-not-owned-err))
;; Gets the owner of the specified token ID.
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? XXXtentation token-id)))
;; Gets the owner of the specified token ID.
(define-read-only (get-last-token-id)
(ok u1))
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae")))
(define-read-only (get-meta (token-id uint))
(if (is-eq token-id u1)
(ok (some {name: "XXXtentation #1", uri: "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae", mime-type: "song/mp4"}))
(ok none)))
(define-read-only (get-nft-meta)
(ok (some {name: "XXXtentation", uri: "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/Let%27s%20Pretend%20We%20Numb.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T172023Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d271daeb06305007bb1a40dfa73339e424f686efcc4c106ce974d117fdd5c2ae", mime-type: "song/mp4"})))
(define-read-only (get-errstr (code uint))
(ok (if (is-eq u401 code)
"nft-not-owned"
(if (is-eq u404 code)
"nft-not-found"
(if (is-eq u405 code)
"sender-equals-recipient"
"unknown-error")))))
;; Initialize the contract
(try! (nft-mint? XXXtentation u1 tx-sender)) | 0xc275e1b3178c11e11f1e7e5086f2267a3c1a662f8fc77002976b487144526bd0 | 14,698 | abort_by_response |
XXXtentation | (define-non-fungible-token XXXtentation uint)
;; Public functions
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant nft-not-found-err (err u404)) ;; not found
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; Transfers tokens to a specified principal.
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and
(is-eq tx-sender (unwrap! (nft-get-owner? XXXtentation token-id) nft-not-found-err))
(is-eq tx-sender sender)
(not (is-eq recipient sender)))
(match (nft-transfer? XXXtentation token-id sender recipient)
success (ok success)
error (nft-transfer-err error))
nft-not-owned-err))
;; Gets the owner of the specified token ID.
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? XXXtentation token-id)))
;; Gets the owner of the specified token ID.
(define-read-only (get-last-token-id)
(ok u1))
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://yh-prod-redeem.s3.dualstack.us-east-1.amazonaws.com/xxxtentaction_drop1/i%20spoke%20to%20the%20devil%20in%20miami.mp3?X-Amz-Security-Token=IQoJb3JpZ2luX2VjECEaCXVzLWVhc3QtMSJHMEUCIQCFpnlzVDBHjzqoL0TGHjlY61cGhpcyvyWmXNCEOE7yVQIgXcgude7boc36lPKL%2FRtsp5I140EypGPrL1DpeHda%2BPcqvQMIqf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARABGgwwMzQ2OTM3Mjc4NjAiDARsWamdl3EM5iH%2BZyqRAy9w4NAmk2RCI8XCtO7kAumsCtnV6h0fvSJPzfPTds6kul7Z2yXGvywt2oxByF1GZ3CmmkAHumdGWLbQ%2FAOHjIU7XYEeExlAUc00ZaVH6PCA%2BTQ5vT498D%2BDt%2FHZV0quvDRy0%2BbFjqzCCMM6bDavpjaQyRJoyJJducZPvuu6VAc%2Fro%2F0NOX%2FkZgVbpZ%2F86Epi%2F%2F%2Fd5vQBi6IpezaUDVcXh8JjPH4SHlnxkkHcsDKOdMhAWiZRggpH%2FgtKTTyiTQF08gEG6odV0vmWhyPgKbXPmMXAHzFprMU6Pj1ChfBEVxD4Kt05ea%2FZwq4Lu3XF4CwcCa%2F%2BWnGoP9eCOcGSrkmDQ1MZ52RYo%2B6%2FnM0fgHgPOKOsXZ3aHTWqRMTkhY6G5plz%2Fvqa78IRJQ7VYE%2BhsiDo7iL0vBLeGrDkMs3kxUmGBjFr5nxQi8yHMZnXfo3L2%2Feju9n6QS4LQg9ZwGPGQaomPWkwNNjxqlX8jxUjXV1r1nsMqZF9t5Evka2mqsM7rBdihoacnF5QqLKObyxW2Cvs82tMILX6oQGOusBbAS5HROXv24Zs1TDi%2BygPTaQnyif5YFCPtDbh2k805z41xn2I8vL0s3gczCrVdCyuvC63SRF%2BG1fob%2F7sv9UPqd3QpbzxCEUmGIhzEtm8%2BADwTprw2cHCET6Qk5QVnNB9CpygLUA1%2BfWe5WmPsytKa0vhE0WRD8IxZzzZ4eZIK9q6etyK972U9T31uYGxcRVu1k%2FEeW4rMBvtXEmh2HZb8ao7nRPqUvByTaRXHzgK%2Fl%2F8s5eH5xVrM1K5220mI4EOliVAg4nOsHbbJaWkHsn4Kpi7AWC4QnR7bDD%2F%2B8fDfq%2BMo70u9kDZHs6Ww%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20210511T170143Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=ASIAQQE7IIZ2GKN3EZ4D%2F20210511%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=9ce7d555e98047c4b1fc12d5b9a87037588c5e197074a1d5317eb9364ad61bfe")))
(define-read-only (get-errstr (code uint))
(ok (if (is-eq u401 code)
"nft-not-owned"
(if (is-eq u404 code)
"nft-not-found"
(if (is-eq u405 code)
"sender-equals-recipient"
"unknown-error")))))
;; Initialize the contract
(try! (nft-mint? XXXtentation u1 tx-sender)) | 0xcf1bf0412dcd795e3b92e0f2c49e3774349aff372eda81dc1da70a4c6a3245ee | 14,701 | success |
thisisnumberone-v2 |
;; Interface definitions
;; (impl-trait 'ST1ESYCGJB5Z5NBHS39XPC70PGC14WAQK5XXNQYDW.nft-interface.transferable-nft-trait)
;; (impl-trait 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-interface.tradable-nft-trait)
(impl-trait 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-trait.nft-trait)
;; contract variables
(define-data-var administrator principal 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ)
(define-data-var mint-price uint u100000)
(define-data-var base-token-uri (string-ascii 256) "https://thisisnumberone.com/mesh/v2/asset/")
(define-data-var mint-counter uint u0)
(define-data-var platform-fee uint u5)
;; constants
(define-constant token-name "thisisnumberone-v2")
(define-constant token-symbol "#1")
;; Non Fungible Token, modeled after ERC-721 via nft-trait
;; Note this is a basic implementation - no support yet for setting approvals for assets
;; NFT are identified by nft-index (uint) which is tied via a reverse lookup to a real world
;; asset hash - SHA 256 32 byte value. The Asset Hash is used to tie arbitrary real world
;; data to the NFT
(define-non-fungible-token my-nft uint)
;; data structures
(define-map nft-lookup {asset-hash: (buff 32), edition: uint} {nft-index: uint})
(define-map nft-data {nft-index: uint} {asset-hash: (buff 32), meta-data-url: (buff 200), max-editions: uint, edition: uint, edition-cost: uint, mint-block-height: uint, series-original: uint})
(define-map nft-sale-data {nft-index: uint} {sale-type: uint, increment-stx: uint, reserve-stx: uint, amount-stx: uint, bidding-end-time: uint, sale-cycle-index: uint})
(define-map nft-beneficiaries {nft-index: uint} { addresses: (list 10 principal), shares: (list 10 uint) })
(define-map nft-bid-history {nft-index: uint, bid-index: uint} {sale-cycle: uint, bidder: principal, amount: uint, app-timestamp: uint})
(define-map nft-offer-history {nft-index: uint, offer-index: uint} {sale-cycle: uint, offerer: principal, app-timestamp: uint, amount: uint, accepted: uint})
;; counters keep track per NFT of the...
;; a) number of editions minted (1 based index)
;; b) number of offers made (0 based index)
;; c) number of bids made (0 based index)
(define-map nft-offer-counter {nft-index: uint} {offer-counter: uint, sale-cycle: uint})
(define-map nft-edition-counter {nft-index: uint} {edition-counter: uint})
(define-map nft-high-bid-counter {nft-index: uint} {high-bid-counter: uint, sale-cycle: uint})
(define-constant percentage-with-twodp u10000000000)
;; (define-constant percentage-with-twodp u10000)
(define-constant not-allowed (err u10))
(define-constant not-found (err u11))
(define-constant amount-not-set (err u12))
(define-constant seller-not-found (err u13))
(define-constant asset-not-registered (err u14))
(define-constant transfer-error (err u15))
(define-constant not-approved-to-sell (err u16))
(define-constant same-spender-err (err u17))
(define-constant failed-to-mint-err (err u18))
(define-constant edition-counter-error (err u19))
(define-constant edition-limit-reached (err u20))
(define-constant user-amount-different (err u21))
(define-constant failed-to-stx-transfer (err u22))
(define-constant failed-to-close-1 (err u23))
(define-constant failed-to-close-2 (err u24))
(define-constant failed-to-close-3 (err u24))
(define-constant cant-pay-mint-price (err u25))
(define-constant editions-error (err u26))
(define-constant payment-error (err u28))
(define-constant payment-address-error (err u33))
(define-constant payment-share-error (err u34))
(define-constant bidding-error (err u35))
(define-constant prevbid-bidding-error (err u36))
(define-constant not-originale (err u37))
(define-constant bidding-opening-error (err u38))
(define-constant bidding-amount-error (err u39))
(define-constant bidding-endtime-error (err u40))
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-constant nft-not-found-err (err u404)) ;; not found
;; interface methods
;; from nft-trait: Last token ID, limited to uint range
;; note decrement as mint counter is the id of the next nft
(define-read-only (get-last-token-id)
(ok (- (var-get mint-counter) u1))
)
;; from nft-trait: URI for metadata associated with the token
(define-read-only (get-token-uri (nftIndex uint))
(ok (some (var-get base-token-uri)))
)
;; from nft-trait: Gets the owner of the 'SPecified token ID.
(define-read-only (get-owner (nftIndex uint))
(ok (nft-get-owner? my-nft nftIndex))
)
;; Transfers tokens to a 'SPecified principal.
(define-public (transfer (nftIndex uint) (owner principal) (recipient principal))
(if (and (is-owner nftIndex owner) (is-eq owner tx-sender))
(match (nft-transfer? my-nft nftIndex owner recipient)
success (ok true)
error (nft-transfer-err error))
nft-not-owned-err)
)
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; public methods
;; --------------
;; the contract administrator can change the contract administrator
(define-public (transfer-administrator (new-administrator principal))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set administrator new-administrator)
(ok true)
)
)
;; the contract administrator can change the transfer fee charged by the contract on sale of tokens
(define-public (change-fee (new-fee uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set platform-fee new-fee)
(ok true)
)
)
;; the contract administrator can change the base uri - where meta data for tokens in this contract
;; are located
(define-public (update-base-token-uri (new-base-token-uri (string-ascii 256)))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set base-token-uri new-base-token-uri)
(ok true)
)
)
;; the contract administrator can change the mint price
(define-public (update-mint-price (new-mint-price uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set mint-price new-mint-price)
(ok true)
)
)
;; The administrator can transfer the balance in the contract to another address
(define-public (transfer-balance (recipient principal))
(let
(
(balance (stx-get-balance (as-contract tx-sender)))
)
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(unwrap! (stx-transfer? balance (as-contract tx-sender) recipient) failed-to-stx-transfer)
(print "refund-bid : refunded bid to biddder")
(ok balance)
)
)
;; adds an offer to the list of offers on an NFT
(define-public (make-offer (nft-index uint) (amount uint) (app-timestamp uint))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerCounter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nft-index}))))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nft-index})) amount-not-set))
)
(asserts! (is-eq saleType u3) not-allowed)
(map-insert nft-offer-history {nft-index: nft-index, offer-index: offerCounter} {sale-cycle: saleCycleIndex, offerer: tx-sender, app-timestamp: app-timestamp, amount: amount, accepted: u0})
(map-set nft-offer-counter {nft-index: nft-index} {sale-cycle: saleCycleIndex, offer-counter: (+ offerCounter u1)})
(ok (+ offerCounter u1))
)
)
;; accept-offer
;; marks offer as accepted and transfers ownership to the recipient
(define-public (accept-offer (nft-index uint) (offer-index uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerer (unwrap! (get offerer (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(app-timestamp (unwrap! (get app-timestamp (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(sale-cycle (unwrap! (get sale-cycle (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(amount (unwrap! (get amount (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
)
(asserts! (is-eq saleType u3) not-allowed)
(map-set nft-offer-history {nft-index: nft-index, offer-index: offer-index} {sale-cycle: sale-cycle, offerer: offerer, app-timestamp: app-timestamp, amount: amount, accepted: u1})
(ok (transfer nft-index owner recipient))
)
)
;; mint a new token
;; asset-hash: sha256 hash of asset file
;; max-editions: maximum number of editions allowed for this asset
;; royalties: a list of priciple/percentages to be be paid from sale price
;;
;; 1. transfer mint price to the administrator
;; 2. mint the token using built in mint function
;; 3. update the two maps - first contains the data indexed by the nft index, second
;; provides a reverse lookup based on the asset hash - this allows tokens to be located
;; from just a knowledge of the original asset.
;; Note series-original in the case of the original in series is just
;; mintCounter - for editions this provides a safety hook back to the original in cases
;; where the asset hash is unknown (ie cant be found from nft-lookup).
(define-public (mint-token (asset-hash (buff 32)) (metaDataUrl (buff 200)) (maxEditions uint) (editionCost uint) (addresses (list 10 principal)) (shares (list 10 uint)))
(let
(
(mintCounter (var-get mint-counter))
(ahash (get asset-hash (map-get? nft-data {nft-index: (var-get mint-counter)})))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
)
(asserts! (> maxEditions u0) editions-error)
(asserts! (> (stx-get-balance tx-sender) (var-get mint-price)) cant-pay-mint-price)
(asserts! (is-none ahash) asset-not-registered)
;; Note: series original is really for later editions to refer back to this one - this one IS the series original
(map-insert nft-data {nft-index: mintCounter} {asset-hash: asset-hash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: u1, edition-cost: editionCost, mint-block-height: block-height, series-original: mintCounter})
;; Note editions are 1 based and <= maxEditions - the one minted here is #1
(map-insert nft-edition-counter {nft-index: mintCounter} {edition-counter: u2})
;; By default we accept offers - sale type can be changed via the UI.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(map-insert nft-lookup {asset-hash: asset-hash, edition: u1} {nft-index: mintCounter})
;; The payment is split between the nft-beneficiaries with share > 0 they are set per edition
(map-insert nft-beneficiaries {nft-index: mintCounter} {addresses: addresses, shares: shares})
;; finally - mint the NFT and step the counter
(if (is-eq tx-sender (var-get administrator))
(print "mint-token : tx-sender is contract - skipping mint price")
(begin
(unwrap! (stx-transfer? (var-get mint-price) tx-sender (var-get administrator)) failed-to-stx-transfer)
(print "mint-token : tx-sender paid mint price")
)
)
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
(print {evt: "mint-token", nftIndex: mintCounter, owner: tx-sender, amount: (var-get mint-price)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
(define-public (mint-edition (nftIndex uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(maxEditions (unwrap! (get max-editions (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCost (unwrap! (get edition-cost (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCounter (unwrap! (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex})) edition-counter-error))
(thisEdition (default-to u0 (get nft-index (map-get? nft-lookup {asset-hash: ahash, edition: editionCounter}))))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
(mintCounter (var-get mint-counter))
)
;; can only mint an edition via buy now or bidding - not offers
(asserts! (is-eq thisEdition u0) edition-counter-error)
;; Note - the edition index is 1 based and incremented before insertion in this method - therefore the test is '<=' here!
(asserts! (<= editionCounter maxEditions) edition-limit-reached)
;; This asserts the first one has been minted already - see mint-token.
(asserts! (> editionCounter u1) edition-counter-error)
;; check the buyer has enough funds..
(asserts! (> (stx-get-balance tx-sender) editionCost) cant-pay-mint-price)
;; set max editions so we know where we are in the series
(map-insert nft-data {nft-index: mintCounter} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: editionCounter, edition-cost: editionCost, mint-block-height: block-height, series-original: nftIndex})
;; put the nft index into the list of editions in the look up map
(map-insert nft-lookup {asset-hash: ahash, edition: editionCounter} {nft-index: mintCounter})
;; mint the NFT and update the counter for the next..
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
;; saleType = 1 (buy now) - split out the payments according to royalties - or roll everything back.
(if (> editionCost u0)
(begin (unwrap! (payment-split nftIndex editionCost tx-sender) failed-to-mint-err) (print "mint-edition : payment split made"))
(print "mint-edition : payment not required")
)
;; (print "mint-edition : payment managed")
;; initialise the sale data - not for sale until the owner sets it.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(print {evt: "mint-edition", nftIndex: nftIndex, owner: tx-sender, edition: editionCounter, amount: editionCost})
;; inncrement the mint counter and edition counter ready for the next edition
(map-set nft-edition-counter {nft-index: nftIndex} {edition-counter: (+ u1 editionCounter)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
;; allow the owner of the series original to set the cost of minting editions
;; the cost for each edition is taken from the series original and so we need to
;; operate on the the original here - ie nftIndex is the index of thee original
;; and NOT the edition andd only the creator of the series original can change this.
(define-public (set-edition-cost (nftIndex uint) (maxEditions uint) (editionCost uint))
(let
(
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(edition (unwrap! (get edition (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(mintBlockHeight (unwrap! (get mint-block-height (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(seriesOriginal (unwrap! (get series-original (map-get? nft-data {nft-index: nftIndex})) not-allowed))
)
(asserts! (is-owner nftIndex tx-sender) nft-not-owned-err)
(asserts! (is-eq nftIndex seriesOriginal) not-originale)
(ok (map-set nft-data {nft-index: nftIndex} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: edition, edition-cost: editionCost, mint-block-height: mintBlockHeight, series-original: seriesOriginal}))
)
)
;; set-sale-data updates the sale type and purchase info for a given NFT. Only the owner can call this method
;; and doing so make the asset transferable by the recipient - on condition of meeting the conditions of sale
;; This is equivalent to the setApprovalForAll method in ERC 721 contracts.
;; Assumption being made here is that all editions have the same sale data associated
(define-public (set-sale-data (nftIndex uint) (sale-type uint) (increment-stx uint) (reserve-stx uint) (amount-stx uint) (bidding-end-time uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
)
(asserts! (not (is-eq saleType u2)) bidding-error)
(print {evt: "set-sale-data", nftIndex: nftIndex, saleType: sale-type, increment: increment-stx, reserve: reserve-stx, amount: amount-stx, biddingEndTime: bidding-end-time})
(if (is-owner nftIndex tx-sender)
;; Note - don't override the sale cyle index here as this is a public method and can be called ad hoc. Sale cycle is update at end of sale!
(if (map-set nft-sale-data {nft-index: nftIndex} {sale-cycle-index: saleCycleIndex, sale-type: sale-type, increment-stx: increment-stx, reserve-stx: reserve-stx, amount-stx: amount-stx, bidding-end-time: bidding-end-time})
(ok nftIndex) not-allowed
)
not-allowed
)
)
)
;; buy-now
;; pay royalties and transfer asset ownership to tx-sender.
;; Checks that:
;; a) asset is registered
;; b) on sale via buy now
;; c) amount is set
;;
(define-public (buy-now (nftIndex uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(ahash (get asset-hash (map-get? nft-data {nft-index: nftIndex})))
)
(asserts! (is-some ahash) asset-not-registered)
(asserts! (is-eq saleType u1) not-approved-to-sell)
(asserts! (> amount u0) amount-not-set)
;; Make the royalty payments - then zero out the sale data and register the transfer
;; (print "buy-now : Make the royalty payments")
(print (unwrap! (payment-split nftIndex amount tx-sender) payment-error))
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
;; (print "buy-now : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(print {evt: "buy-now", nftIndex: nftIndex, owner: owner, recipient: recipient, amount: amount})
(nft-transfer? my-nft nftIndex owner recipient)
)
)
;; opening-bid
;; nft-index: unique index for NFT
;; The opening bid in the given sale cycle a given item.
(define-public (opening-bid (nftIndex uint) (bidAmount uint) (appTimestamp uint))
(let
(
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(biddingEndTime (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(bidCounter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(asserts! (is-eq bidCounter u0) bidding-opening-error)
(asserts! (is-eq bidAmount amount) bidding-amount-error)
(asserts! (> biddingEndTime appTimestamp) bidding-endtime-error)
(print "place-bid : sending this much to; ")
(print bidAmount)
(print (as-contract tx-sender))
(print "place-bid : when")
(print appTimestamp)
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: u0} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: u1, sale-cycle: saleCycle})
(print {evt: "opening-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: bidAmount})
(ok bidAmount)
)
)
(define-private (get-current-bidder (nftIndex uint) (currentBidIndex uint))
(let
(
(currentBidder (unwrap! (get bidder (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)})) bidding-error))
)
(ok currentBidder)
)
)
(define-private (get-current-bid-amount (nftIndex uint) (currentBidIndex uint))
(let
(
(currentAmount (unwrap! (get amount (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)})) bidding-error))
)
(ok currentAmount)
)
)
;; place-bid
;; nft-index: unique index for NFT
;; nextBidAmount: amount the user is bidding - i.e the amount display on th place bid button.
(define-public (place-bid (nftIndex uint) (nextBidAmount uint) (appTimestamp uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amountStart (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(increment (unwrap! (get increment-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(reserve (unwrap! (get reserve-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(currentBidIndex (unwrap! (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex})) not-allowed))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
(owner (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(print "place-bid : assert there is an opening bid - otherwise client calls opening-bid")
(print currentAmount)
(asserts! (> currentAmount u0) user-amount-different)
(asserts! (is-eq nextBidAmount (+ currentAmount increment)) user-amount-different)
;; if (appTimestamp > bidding-end-time) then this is either the winning or a too late bid on the NFT
;; a too late bid will have been rejected as the last bid resets the sale/bidding data on the item.
;; if its the last bid...
;; 1. Refund the currentBid to the bidder
;; 2. move currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
;; (next-bid) we
;; 1. Refund the currentBid to the bidder
;; 2. Insert currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
(print "place-bid : currentBidIndex")
(print currentBidIndex)
(print "place-bid : bidding-end-time")
(print bidding-end-time)
(print "place-bid : appTimestamp")
(print appTimestamp)
(print "place-bid : reserve")
(print reserve)
(if (> appTimestamp bidding-end-time)
(begin
(print "place-bid : bid is after end time refund current bid")
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-stx-transfer)
(if (< nextBidAmount reserve)
;; if this bid is less than reserve & its the last bid then just refund previous bid
(unwrap! (ok true) failed-to-stx-transfer)
(begin
;; WINNING BID - is the FIRST bid after bidding close.
(print "place-bid : Make the royalty payments")
(unwrap! (payment-split nftIndex nextBidAmount tx-sender) payment-error)
(unwrap! (record-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycle u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(print "place-bid : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(unwrap! (nft-transfer? my-nft nftIndex owner tx-sender) failed-to-stx-transfer)
)
)
)
(begin
(print "place-bid : bid is before end time refund current bid from the contract")
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-stx-transfer)
(print "place-bid : and transfer this bid into the contract")
(unwrap! (next-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
)
)
;;
;; NOTE: Above code will only reconcile IF a bid comes in after 'block-time'
;; We may need a manual trigger to end bidding when this doesn't happen - unless there is a
;; to repond to future events / timeouts that I dont know about.
;;
(print {evt: "place-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: nextBidAmount})
(ok true)
)
)
;; Mint subsequent editions of the NFT
;; nft-index: the index of the original NFT in this series of editions.
;; The sale data must have been set on the asset before calling this.
;; The amount is split according to the royalties.
;; The nextBidAmount is passed to avoid concurrency issues - amount on the buy/bid button must
;; equal the amount expected by the contract.
;; close-bidding
;; nft-index: index of the NFT
;; closeType: type of closure, values are;
;; 1 = buy now closure - uses the last bid (thats held in escrow) to transfer the item to the bidder and to pay royalties
;; 2 = refund closure - the last bid gets refunded and sale is closed. The item ownership does not change.
;; Note bidding can also be closed automatically - if a bid is received after the bidding end time.
;; In the context of a 'live auction' items have no end time and are closed by the 'auctioneer'.
(define-public (close-bidding (nftIndex uint) (closeType uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) failed-to-close-1))
(block-time (unwrap! (get-block-info? time u0) not-allowed))
(currentBidIndex (unwrap! (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex})) not-allowed))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
)
(asserts! (or (is-eq closeType u1) (is-eq closeType u2)) failed-to-close-1)
;; only the owner or administrator can call close
(asserts! (or (is-owner nftIndex tx-sender) (unwrap! (is-administrator) failed-to-close-2)) failed-to-close-2)
;; only the administrator can call close BEFORE the end time - note we use the less accurate
;; but fool proof block time here to prevent owner/client code jerry mandering the close function
(asserts! (or (> block-time bidding-end-time) (unwrap! (is-administrator) failed-to-close-3)) failed-to-close-3)
;; Check for a current bid - if none then just reset the sale data to not selling
(if (is-eq currentAmount u0)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(if (is-eq closeType u1)
(begin
;; buy now closure - pay and transfer ownership
;; note that the money to pay with is in the contract!
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "from-contract", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount, currentBidIndex: currentBidIndex})
(unwrap! (payment-split nftIndex currentAmount (as-contract tx-sender)) payment-error)
(unwrap! (nft-transfer? my-nft nftIndex (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err) tx-sender) failed-to-close-2)
)
(begin
;; refund closure - refund the bid and reset sale data
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "refund", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-close-2)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
)
)
)
(print {evt: "close-bidding", nftIndex: nftIndex, closeType: closeType, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok nftIndex)
)
)
;; read only methods
;; ---------------
(define-read-only (get-administrator)
(var-get administrator))
(define-read-only (is-administrator)
(ok (is-eq (var-get administrator) tx-sender)))
(define-read-only (get-base-token-uri)
(var-get base-token-uri))
(define-read-only (get-mint-counter)
(ok (var-get mint-counter))
)
(define-read-only (get-mint-price)
(var-get mint-price))
(define-read-only (get-token-by-index (nftIndex uint))
(ok (get-all-data nftIndex))
)
(define-read-only (get-beneficiaries (nftIndex uint))
(let
(
(beneficiaries (map-get? nft-beneficiaries {nft-index: nftIndex}))
)
(ok beneficiaries)
)
)
(define-read-only (get-offer-at-index (nftIndex uint) (offerIndex uint))
(let
(
(the-offer (map-get? nft-offer-history {nft-index: nftIndex, offer-index: offerIndex}))
)
(ok the-offer)
)
)
(define-read-only (get-bid-at-index (nftIndex uint) (bidIndex uint))
(let
(
(the-bid (map-get? nft-bid-history {nft-index: nftIndex, bid-index: bidIndex}))
)
(ok the-bid)
)
)
;; Get the edition from a knowledge of the #1 edition and the specific edition number
(define-read-only (get-edition-by-hash (asset-hash (buff 32)) (edition uint))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: edition})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-token-by-hash (asset-hash (buff 32)))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: u1})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-contract-data)
(let
(
(the-administrator (var-get administrator))
(the-mint-price (var-get mint-price))
(the-base-token-uri (var-get base-token-uri))
(the-mint-counter (var-get mint-counter))
(the-platform-fee (var-get platform-fee))
(the-token-name token-name)
(the-token-symbol token-symbol)
)
(ok (tuple (administrator the-administrator)
(mintPrice the-mint-price)
(baseTokenUri the-base-token-uri)
(mintCounter the-mint-counter)
(platformFee the-platform-fee)
(tokenName the-token-name)
(tokenSymbol the-token-symbol)))
)
)
(define-private (get-all-data (nftIndex uint))
(let
(
(the-owner (unwrap-panic (nft-get-owner? my-nft nftIndex)))
(the-token-info (map-get? nft-data {nft-index: nftIndex}))
(the-sale-data (map-get? nft-sale-data {nft-index: nftIndex}))
(the-beneficiary-data (map-get? nft-beneficiaries {nft-index: nftIndex}))
(the-edition-counter (default-to u0 (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex}))))
(the-offer-counter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nftIndex}))))
(the-high-bid-counter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
(ok (tuple (offerCounter the-offer-counter)
(bidCounter the-high-bid-counter)
(editionCounter the-edition-counter)
(nftIndex nftIndex)
(tokenInfo the-token-info)
(saleData the-sale-data)
(beneficiaryData the-beneficiary-data)
(owner the-owner)
)
)
)
)
(define-read-only (get-sale-data (nftIndex uint))
(match (map-get? nft-sale-data {nft-index: nftIndex})
mySaleData
(ok mySaleData)
not-found
)
)
(define-read-only (get-token-name)
(ok token-name)
)
(define-read-only (get-token-symbol)
(ok token-symbol)
)
(define-read-only (get-balance)
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(ok (stx-get-balance (as-contract tx-sender)))
)
)
;; private methods
;; ---------------
(define-private (refund-bid (nftIndex uint) (currentBidder principal) (currentAmount uint))
(begin
(unwrap! (as-contract (stx-transfer? currentAmount tx-sender currentBidder)) failed-to-stx-transfer)
(print {evt: "refund-bid", nftIndex: nftIndex, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok true)
)
)
;; need to account for reserve-stx
(define-private (record-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
;; see place-bid for the payment - no need for this (unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {evt: "record-bid", nftIndex: nftIndex, txSender: tx-sender, bidAmount: bidAmount, bidCounter: bidCounter, appTimestamp: appTimestamp, saleCycle: saleCycle})
(ok true)
)
)
(define-private (next-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {appTimestamp: appTimestamp, bidAmount: bidAmount, bidCounter: bidCounter, evt: "next-bid", nftIndex: nftIndex, saleCycle: saleCycle, txSender: tx-sender})
(ok true)
)
)
;; sends payments to each recipient listed in the royalties
;; Note this is called by mint-edition where thee nftIndex actuallt referes to the series orginal and is where the royalties are stored.
(define-private (payment-split (nftIndex uint) (saleAmount uint) (payer principal))
(let
(
(addresses (unwrap! (get addresses (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(shares (unwrap! (get shares (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(split u0)
)
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u0) payment-address-error) (unwrap! (element-at shares u0) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u1) payment-address-error) (unwrap! (element-at shares u1) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u2) payment-address-error) (unwrap! (element-at shares u2) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u3) payment-address-error) (unwrap! (element-at shares u3) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u4) payment-address-error) (unwrap! (element-at shares u4) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u5) payment-address-error) (unwrap! (element-at shares u5) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u6) payment-address-error) (unwrap! (element-at shares u6) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u7) payment-address-error) (unwrap! (element-at shares u7) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u8) payment-address-error) (unwrap! (element-at shares u8) payment-share-error)) payment-share-error))
(print split)
(+ split (unwrap! (pay-royalty payer saleAmount (unwrap! (element-at addresses u9) payment-address-error) (unwrap! (element-at shares u9) payment-share-error)) payment-share-error))
(print {evt: "payment-split", nftIndex: nftIndex, payer: payer, saleAmount: saleAmount, txSender: tx-sender})
(print split)
(ok split)
)
)
;; In the pay-royalty function, the unit of saleAmount is in Satoshi and the share variable is a percentage (ex for 5% it will be equal to 5)
(define-private (pay-royalty (payer principal) (saleAmount uint) (payee principal) (share uint))
(begin
(if (> share u0)
(let
(
(split (/ (* saleAmount share) percentage-with-twodp))
)
;; ignore royalty payment if its to the buyer / tx-sender.
(if (not (is-eq tx-sender payee))
(unwrap! (stx-transfer? split payer payee) transfer-error)
(unwrap! (ok true) transfer-error)
)
(print {evt: "pay-royalty", payee: payee, payer: payer, saleAmount: saleAmount, share: share, txSender: tx-sender})
(ok split)
)
(ok u0)
)
)
)
(define-private (is-owner (nft-index uint) (user principal))
(is-eq user
;; if no owner, return false
(unwrap! (nft-get-owner? my-nft nft-index) false))
)
| 0xe1a321036b9dedf34678f8378d53c64ae6e315d5be50e31161ab2e423a2827e2 | 15,296 | abort_by_response |
nft-approvable-trait | (define-trait nft-approvable-trait
(
;; Last token ID, limited to uint range
(get-last-token-id () (response uint uint))
;; URI for metadata associated with the token
(get-token-uri (uint) (response (optional (string-ascii 256)) uint))
;; Owner of a given token identifier
(get-owner (uint) (response (optional principal) uint))
;; Sets or unsets a user or contract principal who is allowed to call transfer
(set-approval-for (uint principal) (response bool uint))
;; Transfer from the sender to a new principal - must be called by the
;; nft owner or by an approved address
(transfer (uint principal principal) (response bool uint))
)
)
| 0x6f04ffe5c6eec71d44709eb226fd4da8531ac6b46ad196268b2c64a6e20292a4 | 15,302 | success |
thisisnumberone-v2 |
;; Interface definitions
;; test/mocknet
;; (impl-trait 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-approvable-trait.nft-approvable-trait)
;; (impl-trait 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-trait.nft-trait)
;; mainnet
(impl-trait SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-approvable-trait.nft-approvable-trait)
(impl-trait SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
;; contract variables
(define-data-var administrator principal 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ)
(define-data-var mint-price uint u100000)
(define-data-var base-token-uri (string-ascii 256) "https://thisisnumberone.com/mesh/v2/asset/")
(define-data-var mint-counter uint u0)
(define-data-var platform-fee uint u5)
;; constants
(define-constant token-name "thisisnumberone")
(define-constant token-symbol "#1")
;; Non Fungible Token, modeled after ERC-721 via nft-trait
;; Note this is a basic implementation - no support yet for setting approvals for assets
;; NFT are identified by nft-index (uint) which is tied via a reverse lookup to a real world
;; asset hash - SHA 256 32 byte value. The Asset Hash is used to tie arbitrary real world
;; data to the NFT
(define-non-fungible-token my-nft uint)
;; data structures
(define-map nft-approvals {nft-index: uint} {approval: principal})
(define-map nft-lookup {asset-hash: (buff 32), edition: uint} {nft-index: uint})
(define-map nft-data {nft-index: uint} {asset-hash: (buff 32), meta-data-url: (buff 200), max-editions: uint, edition: uint, edition-cost: uint, mint-block-height: uint, series-original: uint})
(define-map nft-sale-data {nft-index: uint} {sale-type: uint, increment-stx: uint, reserve-stx: uint, amount-stx: uint, bidding-end-time: uint, sale-cycle-index: uint})
(define-map nft-beneficiaries {nft-index: uint} { addresses: (list 10 principal), shares: (list 10 uint) })
(define-map nft-bid-history {nft-index: uint, bid-index: uint} {sale-cycle: uint, bidder: principal, amount: uint, app-timestamp: uint})
(define-map nft-offer-history {nft-index: uint, offer-index: uint} {sale-cycle: uint, offerer: principal, app-timestamp: uint, amount: uint, accepted: uint})
;; counters keep track per NFT of the...
;; a) number of editions minted (1 based index)
;; b) number of offers made (0 based index)
;; c) number of bids made (0 based index)
(define-map nft-offer-counter {nft-index: uint} {offer-counter: uint, sale-cycle: uint})
(define-map nft-edition-counter {nft-index: uint} {edition-counter: uint})
(define-map nft-high-bid-counter {nft-index: uint} {high-bid-counter: uint, sale-cycle: uint})
(define-constant percentage-on-secondary u10)
(define-constant percentage-with-twodp u10000000000)
(define-constant not-allowed (err u10))
(define-constant not-found (err u11))
(define-constant amount-not-set (err u12))
(define-constant seller-not-found (err u13))
(define-constant asset-not-registered (err u14))
(define-constant transfer-error (err u15))
(define-constant not-approved-to-sell (err u16))
(define-constant same-spender-err (err u17))
(define-constant failed-to-mint-err (err u18))
(define-constant edition-counter-error (err u19))
(define-constant edition-limit-reached (err u20))
(define-constant user-amount-different (err u21))
(define-constant failed-to-stx-transfer (err u22))
(define-constant failed-to-close-1 (err u23))
(define-constant failed-refund (err u24))
(define-constant failed-to-close-3 (err u24))
(define-constant cant-pay-mint-price (err u25))
(define-constant editions-error (err u26))
(define-constant payment-error (err u28))
(define-constant payment-address-error (err u33))
(define-constant payment-share-error (err u34))
(define-constant bidding-error (err u35))
(define-constant prevbid-bidding-error (err u36))
(define-constant not-originale (err u37))
(define-constant bidding-opening-error (err u38))
(define-constant bidding-amount-error (err u39))
(define-constant bidding-endtime-error (err u40))
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-constant nft-not-found-err (err u404)) ;; not found
;; interface methods
;; from nft-trait: Last token ID, limited to uint range
;; note decrement as mint counter is the id of the next nft
(define-read-only (get-last-token-id)
(ok (- (var-get mint-counter) u1))
)
;; from nft-trait: URI for metadata associated with the token
(define-read-only (get-token-uri (nftIndex uint))
(ok (some (var-get base-token-uri)))
)
;; from nft-trait: Gets the owner of the 'SPecified token ID.
(define-read-only (get-owner (nftIndex uint))
(ok (nft-get-owner? my-nft nftIndex))
)
;; from nft-trait: Gets the owner of the 'SPecified token ID.
(define-read-only (get-approval (nftIndex uint))
(ok (unwrap! (get approval (map-get? nft-approvals {nft-index: nftIndex})) not-found))
)
;; sets an approval principal - allowed to call transfer on owner behalf.
(define-public (set-approval-for (nftIndex uint) (approval principal))
(if (is-owner nftIndex tx-sender)
(begin
(map-set nft-approvals {nft-index: nftIndex} {approval: approval})
(ok true)
)
nft-not-owned-err
)
)
;; Transfers tokens to a 'SPecified principal.
(define-public (transfer (nftIndex uint) (owner principal) (recipient principal))
(if (and (is-owner-or-approval nftIndex owner) (is-owner-or-approval nftIndex tx-sender))
(match (nft-transfer? my-nft nftIndex owner recipient)
success (ok true)
error (nft-transfer-err error))
nft-not-owned-err)
)
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
(define-private (is-owner (nftIndex uint) (user principal))
(is-eq user (unwrap! (nft-get-owner? my-nft nftIndex) false))
)
(define-private (is-approval (nftIndex uint) (user principal))
(is-eq user (unwrap! (get approval (map-get? nft-approvals {nft-index: nftIndex})) false))
)
(define-private (is-owner-or-approval (nftIndex uint) (user principal))
(if (is-owner nftIndex user) true
(if (is-approval nftIndex user) true false)
)
)
;; public methods
;; --------------
;; the contract administrator can change the contract administrator
(define-public (transfer-administrator (new-administrator principal))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set administrator new-administrator)
(ok true)
)
)
;; the contract administrator can change the transfer fee charged by the contract on sale of tokens
(define-public (change-fee (new-fee uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set platform-fee new-fee)
(ok true)
)
)
;; the contract administrator can change the base uri - where meta data for tokens in this contract
;; are located
(define-public (update-base-token-uri (new-base-token-uri (string-ascii 256)))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set base-token-uri new-base-token-uri)
(ok true)
)
)
;; the contract administrator can change the mint price
(define-public (update-mint-price (new-mint-price uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set mint-price new-mint-price)
(ok true)
)
)
;; The administrator can transfer the balance in the contract to another address
(define-public (transfer-balance (recipient principal))
(let
(
(balance (stx-get-balance (as-contract tx-sender)))
)
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(unwrap! (stx-transfer? balance (as-contract tx-sender) recipient) failed-to-stx-transfer)
(print {evt: "transfer-balance", recipient: recipient, balance: balance})
(ok balance)
)
)
;; adds an offer to the list of offers on an NFT
(define-public (make-offer (nft-index uint) (amount uint) (app-timestamp uint))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerCounter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nft-index}))))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nft-index})) amount-not-set))
)
(map-insert nft-offer-history {nft-index: nft-index, offer-index: offerCounter} {sale-cycle: saleCycleIndex, offerer: tx-sender, app-timestamp: app-timestamp, amount: amount, accepted: u0})
(map-set nft-offer-counter {nft-index: nft-index} {sale-cycle: saleCycleIndex, offer-counter: (+ offerCounter u1)})
(ok (+ offerCounter u1))
)
)
;; accept-offer
;; marks offer as accepted and transfers ownership to the recipient
(define-public (accept-offer (nft-index uint) (offer-index uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerer (unwrap! (get offerer (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(app-timestamp (unwrap! (get app-timestamp (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(sale-cycle (unwrap! (get sale-cycle (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(amount (unwrap! (get amount (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
)
(asserts! (is-eq saleType u3) not-allowed)
(map-set nft-offer-history {nft-index: nft-index, offer-index: offer-index} {sale-cycle: sale-cycle, offerer: offerer, app-timestamp: app-timestamp, amount: amount, accepted: u1})
(ok (transfer nft-index owner recipient))
)
)
;; mint a new token
;; asset-hash: sha256 hash of asset file
;; max-editions: maximum number of editions allowed for this asset
;; royalties: a list of priciple/percentages to be be paid from sale price
;;
;; 1. transfer mint price to the administrator
;; 2. mint the token using built in mint function
;; 3. update the two maps - first contains the data indexed by the nft index, second
;; provides a reverse lookup based on the asset hash - this allows tokens to be located
;; from just a knowledge of the original asset.
;; Note series-original in the case of the original in series is just
;; mintCounter - for editions this provides a safety hook back to the original in cases
;; where the asset hash is unknown (ie cant be found from nft-lookup).
(define-public (mint-token (asset-hash (buff 32)) (metaDataUrl (buff 200)) (maxEditions uint) (editionCost uint) (addresses (list 10 principal)) (shares (list 10 uint)))
(let
(
(mintCounter (var-get mint-counter))
(ahash (get asset-hash (map-get? nft-data {nft-index: (var-get mint-counter)})))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
)
(asserts! (> maxEditions u0) editions-error)
(asserts! (> (stx-get-balance tx-sender) (var-get mint-price)) cant-pay-mint-price)
(asserts! (is-none ahash) asset-not-registered)
;; Note: series original is really for later editions to refer back to this one - this one IS the series original
(map-insert nft-data {nft-index: mintCounter} {asset-hash: asset-hash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: u1, edition-cost: editionCost, mint-block-height: block-height, series-original: mintCounter})
;; Note editions are 1 based and <= maxEditions - the one minted here is #1
(map-insert nft-edition-counter {nft-index: mintCounter} {edition-counter: u2})
;; By default we accept offers - sale type can be changed via the UI.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(map-insert nft-lookup {asset-hash: asset-hash, edition: u1} {nft-index: mintCounter})
;; The payment is split between the nft-beneficiaries with share > 0 they are set per edition
(map-insert nft-beneficiaries {nft-index: mintCounter} {addresses: addresses, shares: shares})
;; finally - mint the NFT and step the counter
(if (is-eq tx-sender (var-get administrator))
(print "mint-token : tx-sender is contract - skipping mint price")
(begin
(unwrap! (stx-transfer? (var-get mint-price) tx-sender (var-get administrator)) failed-to-stx-transfer)
(print "mint-token : tx-sender paid mint price")
)
)
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
(print {evt: "mint-token", nftIndex: mintCounter, owner: tx-sender, amount: (var-get mint-price)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
(define-public (mint-edition (nftIndex uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(maxEditions (unwrap! (get max-editions (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCost (unwrap! (get edition-cost (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCounter (unwrap! (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex})) edition-counter-error))
(thisEdition (default-to u0 (get nft-index (map-get? nft-lookup {asset-hash: ahash, edition: editionCounter}))))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
(mintCounter (var-get mint-counter))
)
;; can only mint an edition via buy now or bidding - not offers
(asserts! (is-eq thisEdition u0) edition-counter-error)
;; Note - the edition index is 1 based and incremented before insertion in this method - therefore the test is '<=' here!
(asserts! (<= editionCounter maxEditions) edition-limit-reached)
;; This asserts the first one has been minted already - see mint-token.
(asserts! (> editionCounter u1) edition-counter-error)
;; check the buyer has enough funds..
(asserts! (> (stx-get-balance tx-sender) editionCost) cant-pay-mint-price)
;; set max editions so we know where we are in the series
(map-insert nft-data {nft-index: mintCounter} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: editionCounter, edition-cost: editionCost, mint-block-height: block-height, series-original: nftIndex})
;; put the nft index into the list of editions in the look up map
(map-insert nft-lookup {asset-hash: ahash, edition: editionCounter} {nft-index: mintCounter})
;; mint the NFT and update the counter for the next..
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
;; saleType = 1 (buy now) - split out the payments according to royalties - or roll everything back.
(if (> editionCost u0)
(begin (unwrap! (payment-split nftIndex editionCost tx-sender) failed-to-mint-err) (print "mint-edition : payment split made"))
(print "mint-edition : payment not required")
)
;; (print "mint-edition : payment managed")
;; initialise the sale data - not for sale until the owner sets it.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(print {evt: "mint-edition", nftIndex: nftIndex, owner: tx-sender, edition: editionCounter, amount: editionCost})
;; inncrement the mint counter and edition counter ready for the next edition
(map-set nft-edition-counter {nft-index: nftIndex} {edition-counter: (+ u1 editionCounter)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
;; allow the owner of the series original to set the cost of minting editions
;; the cost for each edition is taken from the series original and so we need to
;; operate on the the original here - ie nftIndex is the index of thee original
;; and NOT the edition andd only the creator of the series original can change this.
(define-public (set-edition-cost (nftIndex uint) (maxEditions uint) (editionCost uint))
(let
(
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(edition (unwrap! (get edition (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(mintBlockHeight (unwrap! (get mint-block-height (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(seriesOriginal (unwrap! (get series-original (map-get? nft-data {nft-index: nftIndex})) not-allowed))
)
(asserts! (is-owner nftIndex tx-sender) nft-not-owned-err)
(asserts! (is-eq nftIndex seriesOriginal) not-originale)
(ok (map-set nft-data {nft-index: nftIndex} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: edition, edition-cost: editionCost, mint-block-height: mintBlockHeight, series-original: seriesOriginal}))
)
)
;; set-sale-data updates the sale type and purchase info for a given NFT. Only the owner can call this method
;; and doing so make the asset transferable by the recipient - on condition of meeting the conditions of sale
;; This is equivalent to the setApprovalForAll method in ERC 721 contracts.
;; Assumption being made here is that all editions have the same sale data associated
(define-public (set-sale-data (nftIndex uint) (sale-type uint) (increment-stx uint) (reserve-stx uint) (amount-stx uint) (bidding-end-time uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
)
(asserts! (not (and (> currentAmount u0) (is-eq saleType u2))) bidding-error)
(print {evt: "set-sale-data", nftIndex: nftIndex, saleType: sale-type, increment: increment-stx, reserve: reserve-stx, amount: amount-stx, biddingEndTime: bidding-end-time})
(if (is-owner nftIndex tx-sender)
;; Note - don't override the sale cyle index here as this is a public method and can be called ad hoc. Sale cycle is update at end of sale!
(if (map-set nft-sale-data {nft-index: nftIndex} {sale-cycle-index: saleCycleIndex, sale-type: sale-type, increment-stx: increment-stx, reserve-stx: reserve-stx, amount-stx: amount-stx, bidding-end-time: bidding-end-time})
(ok nftIndex) not-allowed
)
not-allowed
)
)
)
;; buy-now
;; pay royalties and transfer asset ownership to tx-sender.
;; Checks that:
;; a) asset is registered
;; b) on sale via buy now
;; c) amount is set
;;
(define-public (buy-now (nftIndex uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(ahash (get asset-hash (map-get? nft-data {nft-index: nftIndex})))
)
(asserts! (is-some ahash) asset-not-registered)
(asserts! (is-eq saleType u1) not-approved-to-sell)
(asserts! (> amount u0) amount-not-set)
;; Make the royalty payments - then zero out the sale data and register the transfer
;; (print "buy-now : Make the royalty payments")
(print (unwrap! (payment-split nftIndex amount tx-sender) payment-error))
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
;; (print "buy-now : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(print {evt: "buy-now", nftIndex: nftIndex, owner: owner, recipient: recipient, amount: amount})
(nft-transfer? my-nft nftIndex owner recipient)
)
)
;; opening-bid
;; nft-index: unique index for NFT
;; The opening bid in the given sale cycle a given item.
(define-public (opening-bid (nftIndex uint) (bidAmount uint) (appTimestamp uint))
(let
(
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(biddingEndTime (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(bidCounter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(asserts! (is-eq bidAmount amount) bidding-amount-error)
(asserts! (> biddingEndTime appTimestamp) bidding-endtime-error)
(print "place-bid : sending this much to; ")
(print bidAmount)
(print (as-contract tx-sender))
(print "place-bid : when")
(print appTimestamp)
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {evt: "opening-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: bidAmount})
(ok bidAmount)
)
)
(define-private (get-current-bidder (nftIndex uint) (currentBidIndex uint))
(let
(
(currentBidder (unwrap! (get bidder (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)})) bidding-error))
)
(ok currentBidder)
)
)
(define-private (get-current-bid-amount (nftIndex uint) (currentBidIndex uint))
(if (is-eq currentBidIndex u0)
(ok u0)
(let
(
(currentAmount (default-to u0 (get amount (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)}))))
)
(ok currentAmount)
)
)
)
;; place-bid
;; nft-index: unique index for NFT
;; nextBidAmount: amount the user is bidding - i.e the amount display on th place bid button.
(define-public (place-bid (nftIndex uint) (nextBidAmount uint) (appTimestamp uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amountStart (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(increment (unwrap! (get increment-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(reserve (unwrap! (get reserve-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
(owner (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(print "place-bid : assert there is an opening bid - otherwise client calls opening-bid")
(print currentAmount)
(asserts! (> currentAmount u0) user-amount-different)
(asserts! (is-eq nextBidAmount (+ currentAmount increment)) user-amount-different)
;; if (appTimestamp > bidding-end-time) then this is either the winning or a too late bid on the NFT
;; a too late bid will have been rejected as the last bid resets the sale/bidding data on the item.
;; if its the last bid...
;; 1. Refund the currentBid to the bidder
;; 2. move currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
;; (next-bid) we
;; 1. Refund the currentBid to the bidder
;; 2. Insert currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
(if (> appTimestamp bidding-end-time)
(begin
(print {evt: "place-bid-closure", nftIndex: nftIndex, appTimestamp: appTimestamp, biddingEndTime: bidding-end-time, amount: nextBidAmount, reserve: reserve})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-stx-transfer)
(if (< nextBidAmount reserve)
;; if this bid is less than reserve & its the last bid then just refund previous bid
(unwrap! (ok true) failed-to-stx-transfer)
(begin
;; WINNING BID - is the FIRST bid after bidding close.
(print "place-bid : Make the royalty payments")
(unwrap! (payment-split nftIndex nextBidAmount tx-sender) payment-error)
(unwrap! (record-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycle u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(print "place-bid : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(unwrap! (nft-transfer? my-nft nftIndex owner tx-sender) failed-to-stx-transfer)
)
)
)
(begin
(print {evt: "place-bid-refund", nftIndex: nftIndex, appTimestamp: appTimestamp, biddingEndTime: bidding-end-time, amount: nextBidAmount})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-refund)
(unwrap! (next-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
)
)
;;
;; NOTE: Above code will only reconcile IF a bid comes in after 'block-time'
;; We may need a manual trigger to end bidding when this doesn't happen - unless there is a
;; to repond to future events / timeouts that I dont know about.
;;
(print {evt: "place-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: nextBidAmount})
(ok true)
)
)
;; Mint subsequent editions of the NFT
;; nft-index: the index of the original NFT in this series of editions.
;; The sale data must have been set on the asset before calling this.
;; The amount is split according to the royalties.
;; The nextBidAmount is passed to avoid concurrency issues - amount on the buy/bid button must
;; equal the amount expected by the contract.
;; close-bidding
;; nft-index: index of the NFT
;; closeType: type of closure, values are;
;; 1 = buy now closure - uses the last bid (thats held in escrow) to transfer the item to the bidder and to pay royalties
;; 2 = refund closure - the last bid gets refunded and sale is closed. The item ownership does not change.
;; Note bidding can also be closed automatically - if a bid is received after the bidding end time.
;; In the context of a 'live auction' items have no end time and are closed by the 'auctioneer'.
(define-public (close-bidding (nftIndex uint) (closeType uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) failed-to-close-1))
(block-time (unwrap! (get-block-info? time u0) not-allowed))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
)
(asserts! (or (is-eq closeType u1) (is-eq closeType u2)) failed-to-close-1)
;; only the owner or administrator can call close
(asserts! (or (is-owner nftIndex tx-sender) (unwrap! (is-administrator) not-allowed)) not-allowed)
;; only the administrator can call close BEFORE the end time - note we use the less accurate
;; but fool proof block time here to prevent owner/client code jerry mandering the close function
(asserts! (or (> block-time bidding-end-time) (unwrap! (is-administrator) failed-to-close-3)) failed-to-close-3)
;; Check for a current bid - if none then just reset the sale data to not selling
(if (is-eq currentAmount u0)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(if (is-eq closeType u1)
(begin
;; buy now closure - pay and transfer ownership
;; note that the money to pay with is in the contract!
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "from-contract", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount, currentBidIndex: currentBidIndex})
(unwrap! (payment-split nftIndex currentAmount (as-contract tx-sender)) payment-error)
(unwrap! (nft-transfer? my-nft nftIndex (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err) tx-sender) transfer-error)
)
(begin
;; refund closure - refund the bid and reset sale data
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "refund", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-refund)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
)
)
)
(print {evt: "close-bidding", nftIndex: nftIndex, closeType: closeType, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok nftIndex)
)
)
;; read only methods
;; ---------------
(define-read-only (get-administrator)
(var-get administrator))
(define-read-only (is-administrator)
(ok (is-eq (var-get administrator) tx-sender)))
(define-read-only (get-base-token-uri)
(var-get base-token-uri))
(define-read-only (get-mint-counter)
(ok (var-get mint-counter))
)
(define-read-only (get-mint-price)
(var-get mint-price))
(define-read-only (get-token-by-index (nftIndex uint))
(ok (get-all-data nftIndex))
)
(define-read-only (get-beneficiaries (nftIndex uint))
(let
(
(beneficiaries (map-get? nft-beneficiaries {nft-index: nftIndex}))
)
(ok beneficiaries)
)
)
(define-read-only (get-offer-at-index (nftIndex uint) (offerIndex uint))
(let
(
(the-offer (map-get? nft-offer-history {nft-index: nftIndex, offer-index: offerIndex}))
)
(ok the-offer)
)
)
(define-read-only (get-bid-at-index (nftIndex uint) (bidIndex uint))
(let
(
(the-bid (map-get? nft-bid-history {nft-index: nftIndex, bid-index: bidIndex}))
)
(ok the-bid)
)
)
;; Get the edition from a knowledge of the #1 edition and the specific edition number
(define-read-only (get-edition-by-hash (asset-hash (buff 32)) (edition uint))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: edition})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-token-by-hash (asset-hash (buff 32)))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: u1})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-contract-data)
(let
(
(the-administrator (var-get administrator))
(the-mint-price (var-get mint-price))
(the-base-token-uri (var-get base-token-uri))
(the-mint-counter (var-get mint-counter))
(the-platform-fee (var-get platform-fee))
(the-token-name token-name)
(the-token-symbol token-symbol)
)
(ok (tuple (administrator the-administrator)
(mintPrice the-mint-price)
(baseTokenUri the-base-token-uri)
(mintCounter the-mint-counter)
(platformFee the-platform-fee)
(tokenName the-token-name)
(tokenSymbol the-token-symbol)))
)
)
(define-private (get-all-data (nftIndex uint))
(let
(
(the-owner (unwrap-panic (nft-get-owner? my-nft nftIndex)))
(the-token-info (map-get? nft-data {nft-index: nftIndex}))
(the-sale-data (map-get? nft-sale-data {nft-index: nftIndex}))
(the-beneficiary-data (map-get? nft-beneficiaries {nft-index: nftIndex}))
(the-edition-counter (default-to u0 (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex}))))
(the-offer-counter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nftIndex}))))
(the-high-bid-counter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
(ok (tuple (offerCounter the-offer-counter)
(bidCounter the-high-bid-counter)
(editionCounter the-edition-counter)
(nftIndex nftIndex)
(tokenInfo the-token-info)
(saleData the-sale-data)
(beneficiaryData the-beneficiary-data)
(owner the-owner)
)
)
)
)
(define-read-only (get-sale-data (nftIndex uint))
(match (map-get? nft-sale-data {nft-index: nftIndex})
mySaleData
(ok mySaleData)
not-found
)
)
(define-read-only (get-token-name)
(ok token-name)
)
(define-read-only (get-token-symbol)
(ok token-symbol)
)
(define-read-only (get-balance)
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(ok (stx-get-balance (as-contract tx-sender)))
)
)
;; private methods
;; ---------------
(define-private (refund-bid (nftIndex uint) (currentBidder principal) (currentAmount uint))
(begin
(unwrap! (as-contract (stx-transfer? currentAmount tx-sender currentBidder)) failed-to-stx-transfer)
(print {evt: "refund-bid", nftIndex: nftIndex, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok true)
)
)
;; need to account for reserve-stx
(define-private (record-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
;; see place-bid for the payment - no need for this (unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {evt: "record-bid", nftIndex: nftIndex, txSender: tx-sender, bidAmount: bidAmount, bidCounter: bidCounter, appTimestamp: appTimestamp, saleCycle: saleCycle})
(ok true)
)
)
(define-private (next-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {appTimestamp: appTimestamp, bidAmount: bidAmount, bidCounter: bidCounter, evt: "next-bid", nftIndex: nftIndex, saleCycle: saleCycle, txSender: tx-sender})
(ok true)
)
)
;; sends payments to each recipient listed in the royalties
;; Note this is called by mint-edition where thee nftIndex actuallt referes to the series orginal and is where the royalties are stored.
(define-private (payment-split (nftIndex uint) (saleAmount uint) (payer principal))
(let
(
(addresses (unwrap! (get addresses (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(shares (unwrap! (get shares (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(split u0)
;; If secondary sale (sale-cycle > 1) - the seller gets half the sale value and each royalty payment is half the original amount
(scalor (if (> (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set) u1)
percentage-on-secondary u1))
)
(if (is-eq scalor percentage-on-secondary)
;; If secondary sale - pay the seller then split the royalties
(unwrap! (stx-transfer? (/ (* saleAmount (- u100 percentage-on-secondary)) u100) payer (unwrap! (nft-get-owner? my-nft nftIndex) payment-share-error)) transfer-error)
;; Primary sale - split the royalties
true
)
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u0) payment-address-error) (unwrap! (element-at shares u0) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u1) payment-address-error) (unwrap! (element-at shares u1) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u2) payment-address-error) (unwrap! (element-at shares u2) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u3) payment-address-error) (unwrap! (element-at shares u3) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u4) payment-address-error) (unwrap! (element-at shares u4) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u5) payment-address-error) (unwrap! (element-at shares u5) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u6) payment-address-error) (unwrap! (element-at shares u6) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u7) payment-address-error) (unwrap! (element-at shares u7) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u8) payment-address-error) (unwrap! (element-at shares u8) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u9) payment-address-error) (unwrap! (element-at shares u9) payment-share-error)) payment-share-error))
(print {evt: "payment-split", nftIndex: nftIndex, scalor: scalor, payer: payer, saleAmount: saleAmount, seller: (/ (* saleAmount (- u100 percentage-on-secondary)) u100), txSender: tx-sender})
(ok split)
)
)
;; unit of saleAmount is in Satoshi and the share variable is a percentage (ex for 5% it will be equal to 5)
;; also the scalor is 1 on first purchase - direct from artist and 2 for secondary sales - so the seller gets half the
;; sale value and each royalty address gets half their original amount.
(define-private (pay-royalty (scalor uint) (payer principal) (saleAmount uint) (payee principal) (share uint))
(begin
(if (> share u0)
(let
(
(split (/ (* saleAmount (/ share scalor)) percentage-with-twodp))
)
;; ignore royalty payment if its to the buyer / tx-sender.
(if (not (is-eq tx-sender payee))
(unwrap! (stx-transfer? split payer payee) transfer-error)
(unwrap! (ok true) transfer-error)
)
(print {evt: "pay-royalty-primary", payee: payee, payer: payer, saleAmount: saleAmount, scalor: scalor, share: share, split: split, txSender: tx-sender})
(ok split)
)
(ok u0)
)
)
)
| 0x7bc76ce858c687b3502c3d30a25ce60a68919720814cc2dceec3ccf0cb5159f4 | 15,305 | abort_by_response |
thisisnumberone-v2 |
;; Interface definitions
;; test/mocknet
;; (impl-trait 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-approvable-trait.nft-approvable-trait)
;; (impl-trait 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-trait.nft-trait)
;; mainnet
;; (impl-trait SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-approvable-trait.nft-approvable-trait)
;; (impl-trait SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
;; contract variables
(define-data-var administrator principal 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ)
(define-data-var mint-price uint u100000)
(define-data-var base-token-uri (string-ascii 256) "https://thisisnumberone.com/mesh/v2/asset/")
(define-data-var mint-counter uint u0)
(define-data-var platform-fee uint u5)
;; constants
(define-constant token-name "params.tokenName")
(define-constant token-symbol "#1")
;; Non Fungible Token, modeled after ERC-721 via nft-trait
;; Note this is a basic implementation - no support yet for setting approvals for assets
;; NFT are identified by nft-index (uint) which is tied via a reverse lookup to a real world
;; asset hash - SHA 256 32 byte value. The Asset Hash is used to tie arbitrary real world
;; data to the NFT
(define-non-fungible-token my-nft uint)
;; data structures
(define-map nft-approvals {nft-index: uint} {approval: principal})
(define-map nft-lookup {asset-hash: (buff 32), edition: uint} {nft-index: uint})
(define-map nft-data {nft-index: uint} {asset-hash: (buff 32), meta-data-url: (buff 200), max-editions: uint, edition: uint, edition-cost: uint, mint-block-height: uint, series-original: uint})
(define-map nft-sale-data {nft-index: uint} {sale-type: uint, increment-stx: uint, reserve-stx: uint, amount-stx: uint, bidding-end-time: uint, sale-cycle-index: uint})
(define-map nft-beneficiaries {nft-index: uint} { addresses: (list 10 principal), shares: (list 10 uint) })
(define-map nft-bid-history {nft-index: uint, bid-index: uint} {sale-cycle: uint, bidder: principal, amount: uint, app-timestamp: uint})
(define-map nft-offer-history {nft-index: uint, offer-index: uint} {sale-cycle: uint, offerer: principal, app-timestamp: uint, amount: uint, accepted: uint})
;; counters keep track per NFT of the...
;; a) number of editions minted (1 based index)
;; b) number of offers made (0 based index)
;; c) number of bids made (0 based index)
(define-map nft-offer-counter {nft-index: uint} {offer-counter: uint, sale-cycle: uint})
(define-map nft-edition-counter {nft-index: uint} {edition-counter: uint})
(define-map nft-high-bid-counter {nft-index: uint} {high-bid-counter: uint, sale-cycle: uint})
(define-constant percentage-on-secondary u10)
(define-constant percentage-with-twodp u10000000000)
(define-constant not-allowed (err u10))
(define-constant not-found (err u11))
(define-constant amount-not-set (err u12))
(define-constant seller-not-found (err u13))
(define-constant asset-not-registered (err u14))
(define-constant transfer-error (err u15))
(define-constant not-approved-to-sell (err u16))
(define-constant same-spender-err (err u17))
(define-constant failed-to-mint-err (err u18))
(define-constant edition-counter-error (err u19))
(define-constant edition-limit-reached (err u20))
(define-constant user-amount-different (err u21))
(define-constant failed-to-stx-transfer (err u22))
(define-constant failed-to-close-1 (err u23))
(define-constant failed-refund (err u24))
(define-constant failed-to-close-3 (err u24))
(define-constant cant-pay-mint-price (err u25))
(define-constant editions-error (err u26))
(define-constant payment-error (err u28))
(define-constant payment-address-error (err u33))
(define-constant payment-share-error (err u34))
(define-constant bidding-error (err u35))
(define-constant prevbid-bidding-error (err u36))
(define-constant not-originale (err u37))
(define-constant bidding-opening-error (err u38))
(define-constant bidding-amount-error (err u39))
(define-constant bidding-endtime-error (err u40))
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-constant nft-not-found-err (err u404)) ;; not found
;; interface methods
;; from nft-trait: Last token ID, limited to uint range
;; note decrement as mint counter is the id of the next nft
(define-read-only (get-last-token-id)
(ok (- (var-get mint-counter) u1))
)
;; from nft-trait: URI for metadata associated with the token
(define-read-only (get-token-uri (nftIndex uint))
(ok (some (var-get base-token-uri)))
)
;; from nft-trait: Gets the owner of the 'SPecified token ID.
(define-read-only (get-owner (nftIndex uint))
(ok (nft-get-owner? my-nft nftIndex))
)
;; from nft-trait: Gets the owner of the 'SPecified token ID.
(define-read-only (get-approval (nftIndex uint))
(ok (unwrap! (get approval (map-get? nft-approvals {nft-index: nftIndex})) not-found))
)
;; sets an approval principal - allowed to call transfer on owner behalf.
(define-public (set-approval-for (nftIndex uint) (approval principal))
(if (is-owner nftIndex tx-sender)
(begin
(map-set nft-approvals {nft-index: nftIndex} {approval: approval})
(ok true)
)
nft-not-owned-err
)
)
;; Transfers tokens to a 'SPecified principal.
(define-public (transfer (nftIndex uint) (owner principal) (recipient principal))
(if (and (is-owner-or-approval nftIndex owner) (is-owner-or-approval nftIndex tx-sender))
(match (nft-transfer? my-nft nftIndex owner recipient)
success (ok true)
error (nft-transfer-err error))
nft-not-owned-err)
)
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
(define-private (is-owner (nftIndex uint) (user principal))
(is-eq user (unwrap! (nft-get-owner? my-nft nftIndex) false))
)
(define-private (is-approval (nftIndex uint) (user principal))
(is-eq user (unwrap! (get approval (map-get? nft-approvals {nft-index: nftIndex})) false))
)
(define-private (is-owner-or-approval (nftIndex uint) (user principal))
(if (is-owner nftIndex user) true
(if (is-approval nftIndex user) true false)
)
)
;; public methods
;; --------------
;; the contract administrator can change the contract administrator
(define-public (transfer-administrator (new-administrator principal))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set administrator new-administrator)
(ok true)
)
)
;; the contract administrator can change the transfer fee charged by the contract on sale of tokens
(define-public (change-fee (new-fee uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set platform-fee new-fee)
(ok true)
)
)
;; the contract administrator can change the base uri - where meta data for tokens in this contract
;; are located
(define-public (update-base-token-uri (new-base-token-uri (string-ascii 256)))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set base-token-uri new-base-token-uri)
(ok true)
)
)
;; the contract administrator can change the mint price
(define-public (update-mint-price (new-mint-price uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set mint-price new-mint-price)
(ok true)
)
)
;; The administrator can transfer the balance in the contract to another address
(define-public (transfer-balance (recipient principal))
(let
(
(balance (stx-get-balance (as-contract tx-sender)))
)
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(unwrap! (stx-transfer? balance (as-contract tx-sender) recipient) failed-to-stx-transfer)
(print {evt: "transfer-balance", recipient: recipient, balance: balance})
(ok balance)
)
)
;; adds an offer to the list of offers on an NFT
(define-public (make-offer (nft-index uint) (amount uint) (app-timestamp uint))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerCounter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nft-index}))))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nft-index})) amount-not-set))
)
(map-insert nft-offer-history {nft-index: nft-index, offer-index: offerCounter} {sale-cycle: saleCycleIndex, offerer: tx-sender, app-timestamp: app-timestamp, amount: amount, accepted: u0})
(map-set nft-offer-counter {nft-index: nft-index} {sale-cycle: saleCycleIndex, offer-counter: (+ offerCounter u1)})
(ok (+ offerCounter u1))
)
)
;; accept-offer
;; marks offer as accepted and transfers ownership to the recipient
(define-public (accept-offer (nft-index uint) (offer-index uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerer (unwrap! (get offerer (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(app-timestamp (unwrap! (get app-timestamp (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(sale-cycle (unwrap! (get sale-cycle (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(amount (unwrap! (get amount (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
)
(asserts! (is-eq saleType u3) not-allowed)
(map-set nft-offer-history {nft-index: nft-index, offer-index: offer-index} {sale-cycle: sale-cycle, offerer: offerer, app-timestamp: app-timestamp, amount: amount, accepted: u1})
(ok (transfer nft-index owner recipient))
)
)
;; mint a new token
;; asset-hash: sha256 hash of asset file
;; max-editions: maximum number of editions allowed for this asset
;; royalties: a list of priciple/percentages to be be paid from sale price
;;
;; 1. transfer mint price to the administrator
;; 2. mint the token using built in mint function
;; 3. update the two maps - first contains the data indexed by the nft index, second
;; provides a reverse lookup based on the asset hash - this allows tokens to be located
;; from just a knowledge of the original asset.
;; Note series-original in the case of the original in series is just
;; mintCounter - for editions this provides a safety hook back to the original in cases
;; where the asset hash is unknown (ie cant be found from nft-lookup).
(define-public (mint-token (asset-hash (buff 32)) (metaDataUrl (buff 200)) (maxEditions uint) (editionCost uint) (addresses (list 10 principal)) (shares (list 10 uint)))
(let
(
(mintCounter (var-get mint-counter))
(ahash (get asset-hash (map-get? nft-data {nft-index: (var-get mint-counter)})))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
)
(asserts! (> maxEditions u0) editions-error)
(asserts! (> (stx-get-balance tx-sender) (var-get mint-price)) cant-pay-mint-price)
(asserts! (is-none ahash) asset-not-registered)
;; Note: series original is really for later editions to refer back to this one - this one IS the series original
(map-insert nft-data {nft-index: mintCounter} {asset-hash: asset-hash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: u1, edition-cost: editionCost, mint-block-height: block-height, series-original: mintCounter})
;; Note editions are 1 based and <= maxEditions - the one minted here is #1
(map-insert nft-edition-counter {nft-index: mintCounter} {edition-counter: u2})
;; By default we accept offers - sale type can be changed via the UI.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(map-insert nft-lookup {asset-hash: asset-hash, edition: u1} {nft-index: mintCounter})
;; The payment is split between the nft-beneficiaries with share > 0 they are set per edition
(map-insert nft-beneficiaries {nft-index: mintCounter} {addresses: addresses, shares: shares})
;; finally - mint the NFT and step the counter
(if (is-eq tx-sender (var-get administrator))
(print "mint-token : tx-sender is contract - skipping mint price")
(begin
(unwrap! (stx-transfer? (var-get mint-price) tx-sender (var-get administrator)) failed-to-stx-transfer)
(print "mint-token : tx-sender paid mint price")
)
)
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
(print {evt: "mint-token", nftIndex: mintCounter, owner: tx-sender, amount: (var-get mint-price)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
(define-public (mint-edition (nftIndex uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(maxEditions (unwrap! (get max-editions (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCost (unwrap! (get edition-cost (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCounter (unwrap! (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex})) edition-counter-error))
(thisEdition (default-to u0 (get nft-index (map-get? nft-lookup {asset-hash: ahash, edition: editionCounter}))))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
(mintCounter (var-get mint-counter))
)
;; can only mint an edition via buy now or bidding - not offers
(asserts! (is-eq thisEdition u0) edition-counter-error)
;; Note - the edition index is 1 based and incremented before insertion in this method - therefore the test is '<=' here!
(asserts! (<= editionCounter maxEditions) edition-limit-reached)
;; This asserts the first one has been minted already - see mint-token.
(asserts! (> editionCounter u1) edition-counter-error)
;; check the buyer has enough funds..
(asserts! (> (stx-get-balance tx-sender) editionCost) cant-pay-mint-price)
;; set max editions so we know where we are in the series
(map-insert nft-data {nft-index: mintCounter} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: editionCounter, edition-cost: editionCost, mint-block-height: block-height, series-original: nftIndex})
;; put the nft index into the list of editions in the look up map
(map-insert nft-lookup {asset-hash: ahash, edition: editionCounter} {nft-index: mintCounter})
;; mint the NFT and update the counter for the next..
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
;; saleType = 1 (buy now) - split out the payments according to royalties - or roll everything back.
(if (> editionCost u0)
(begin (unwrap! (payment-split nftIndex editionCost tx-sender) failed-to-mint-err) (print "mint-edition : payment split made"))
(print "mint-edition : payment not required")
)
;; (print "mint-edition : payment managed")
;; initialise the sale data - not for sale until the owner sets it.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(print {evt: "mint-edition", nftIndex: nftIndex, owner: tx-sender, edition: editionCounter, amount: editionCost})
;; inncrement the mint counter and edition counter ready for the next edition
(map-set nft-edition-counter {nft-index: nftIndex} {edition-counter: (+ u1 editionCounter)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
;; allow the owner of the series original to set the cost of minting editions
;; the cost for each edition is taken from the series original and so we need to
;; operate on the the original here - ie nftIndex is the index of thee original
;; and NOT the edition andd only the creator of the series original can change this.
(define-public (set-edition-cost (nftIndex uint) (maxEditions uint) (editionCost uint))
(let
(
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(edition (unwrap! (get edition (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(mintBlockHeight (unwrap! (get mint-block-height (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(seriesOriginal (unwrap! (get series-original (map-get? nft-data {nft-index: nftIndex})) not-allowed))
)
(asserts! (is-owner nftIndex tx-sender) nft-not-owned-err)
(asserts! (is-eq nftIndex seriesOriginal) not-originale)
(ok (map-set nft-data {nft-index: nftIndex} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: edition, edition-cost: editionCost, mint-block-height: mintBlockHeight, series-original: seriesOriginal}))
)
)
;; set-sale-data updates the sale type and purchase info for a given NFT. Only the owner can call this method
;; and doing so make the asset transferable by the recipient - on condition of meeting the conditions of sale
;; This is equivalent to the setApprovalForAll method in ERC 721 contracts.
;; Assumption being made here is that all editions have the same sale data associated
(define-public (set-sale-data (nftIndex uint) (sale-type uint) (increment-stx uint) (reserve-stx uint) (amount-stx uint) (bidding-end-time uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
)
(asserts! (not (and (> currentAmount u0) (is-eq saleType u2))) bidding-error)
(print {evt: "set-sale-data", nftIndex: nftIndex, saleType: sale-type, increment: increment-stx, reserve: reserve-stx, amount: amount-stx, biddingEndTime: bidding-end-time})
(if (is-owner nftIndex tx-sender)
;; Note - don't override the sale cyle index here as this is a public method and can be called ad hoc. Sale cycle is update at end of sale!
(if (map-set nft-sale-data {nft-index: nftIndex} {sale-cycle-index: saleCycleIndex, sale-type: sale-type, increment-stx: increment-stx, reserve-stx: reserve-stx, amount-stx: amount-stx, bidding-end-time: bidding-end-time})
(ok nftIndex) not-allowed
)
not-allowed
)
)
)
;; buy-now
;; pay royalties and transfer asset ownership to tx-sender.
;; Checks that:
;; a) asset is registered
;; b) on sale via buy now
;; c) amount is set
;;
(define-public (buy-now (nftIndex uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(ahash (get asset-hash (map-get? nft-data {nft-index: nftIndex})))
)
(asserts! (is-some ahash) asset-not-registered)
(asserts! (is-eq saleType u1) not-approved-to-sell)
(asserts! (> amount u0) amount-not-set)
;; Make the royalty payments - then zero out the sale data and register the transfer
;; (print "buy-now : Make the royalty payments")
(print (unwrap! (payment-split nftIndex amount tx-sender) payment-error))
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
;; (print "buy-now : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(print {evt: "buy-now", nftIndex: nftIndex, owner: owner, recipient: recipient, amount: amount})
(nft-transfer? my-nft nftIndex owner recipient)
)
)
;; opening-bid
;; nft-index: unique index for NFT
;; The opening bid in the given sale cycle a given item.
(define-public (opening-bid (nftIndex uint) (bidAmount uint) (appTimestamp uint))
(let
(
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(biddingEndTime (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(bidCounter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(asserts! (is-eq bidAmount amount) bidding-amount-error)
(asserts! (> biddingEndTime appTimestamp) bidding-endtime-error)
(print "place-bid : sending this much to; ")
(print bidAmount)
(print (as-contract tx-sender))
(print "place-bid : when")
(print appTimestamp)
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {evt: "opening-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: bidAmount})
(ok bidAmount)
)
)
(define-private (get-current-bidder (nftIndex uint) (currentBidIndex uint))
(let
(
(currentBidder (unwrap! (get bidder (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)})) bidding-error))
)
(ok currentBidder)
)
)
(define-private (get-current-bid-amount (nftIndex uint) (currentBidIndex uint))
(if (is-eq currentBidIndex u0)
(ok u0)
(let
(
(currentAmount (default-to u0 (get amount (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)}))))
)
(ok currentAmount)
)
)
)
;; place-bid
;; nft-index: unique index for NFT
;; nextBidAmount: amount the user is bidding - i.e the amount display on th place bid button.
(define-public (place-bid (nftIndex uint) (nextBidAmount uint) (appTimestamp uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amountStart (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(increment (unwrap! (get increment-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(reserve (unwrap! (get reserve-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
(owner (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(print "place-bid : assert there is an opening bid - otherwise client calls opening-bid")
(print currentAmount)
(asserts! (> currentAmount u0) user-amount-different)
(asserts! (is-eq nextBidAmount (+ currentAmount increment)) user-amount-different)
;; if (appTimestamp > bidding-end-time) then this is either the winning or a too late bid on the NFT
;; a too late bid will have been rejected as the last bid resets the sale/bidding data on the item.
;; if its the last bid...
;; 1. Refund the currentBid to the bidder
;; 2. move currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
;; (next-bid) we
;; 1. Refund the currentBid to the bidder
;; 2. Insert currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
(if (> appTimestamp bidding-end-time)
(begin
(print {evt: "place-bid-closure", nftIndex: nftIndex, appTimestamp: appTimestamp, biddingEndTime: bidding-end-time, amount: nextBidAmount, reserve: reserve})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-stx-transfer)
(if (< nextBidAmount reserve)
;; if this bid is less than reserve & its the last bid then just refund previous bid
(unwrap! (ok true) failed-to-stx-transfer)
(begin
;; WINNING BID - is the FIRST bid after bidding close.
(print "place-bid : Make the royalty payments")
(unwrap! (payment-split nftIndex nextBidAmount tx-sender) payment-error)
(unwrap! (record-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycle u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(print "place-bid : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(unwrap! (nft-transfer? my-nft nftIndex owner tx-sender) failed-to-stx-transfer)
)
)
)
(begin
(print {evt: "place-bid-refund", nftIndex: nftIndex, appTimestamp: appTimestamp, biddingEndTime: bidding-end-time, amount: nextBidAmount})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-refund)
(unwrap! (next-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
)
)
;;
;; NOTE: Above code will only reconcile IF a bid comes in after 'block-time'
;; We may need a manual trigger to end bidding when this doesn't happen - unless there is a
;; to repond to future events / timeouts that I dont know about.
;;
(print {evt: "place-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: nextBidAmount})
(ok true)
)
)
;; Mint subsequent editions of the NFT
;; nft-index: the index of the original NFT in this series of editions.
;; The sale data must have been set on the asset before calling this.
;; The amount is split according to the royalties.
;; The nextBidAmount is passed to avoid concurrency issues - amount on the buy/bid button must
;; equal the amount expected by the contract.
;; close-bidding
;; nft-index: index of the NFT
;; closeType: type of closure, values are;
;; 1 = buy now closure - uses the last bid (thats held in escrow) to transfer the item to the bidder and to pay royalties
;; 2 = refund closure - the last bid gets refunded and sale is closed. The item ownership does not change.
;; Note bidding can also be closed automatically - if a bid is received after the bidding end time.
;; In the context of a 'live auction' items have no end time and are closed by the 'auctioneer'.
(define-public (close-bidding (nftIndex uint) (closeType uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) failed-to-close-1))
(block-time (unwrap! (get-block-info? time u0) not-allowed))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
)
(asserts! (or (is-eq closeType u1) (is-eq closeType u2)) failed-to-close-1)
;; only the owner or administrator can call close
(asserts! (or (is-owner nftIndex tx-sender) (unwrap! (is-administrator) not-allowed)) not-allowed)
;; only the administrator can call close BEFORE the end time - note we use the less accurate
;; but fool proof block time here to prevent owner/client code jerry mandering the close function
(asserts! (or (> block-time bidding-end-time) (unwrap! (is-administrator) failed-to-close-3)) failed-to-close-3)
;; Check for a current bid - if none then just reset the sale data to not selling
(if (is-eq currentAmount u0)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(if (is-eq closeType u1)
(begin
;; buy now closure - pay and transfer ownership
;; note that the money to pay with is in the contract!
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "from-contract", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount, currentBidIndex: currentBidIndex})
(unwrap! (payment-split nftIndex currentAmount (as-contract tx-sender)) payment-error)
(unwrap! (nft-transfer? my-nft nftIndex (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err) tx-sender) transfer-error)
)
(begin
;; refund closure - refund the bid and reset sale data
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "refund", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-refund)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
)
)
)
(print {evt: "close-bidding", nftIndex: nftIndex, closeType: closeType, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok nftIndex)
)
)
;; read only methods
;; ---------------
(define-read-only (get-administrator)
(var-get administrator))
(define-read-only (is-administrator)
(ok (is-eq (var-get administrator) tx-sender)))
(define-read-only (get-base-token-uri)
(var-get base-token-uri))
(define-read-only (get-mint-counter)
(ok (var-get mint-counter))
)
(define-read-only (get-mint-price)
(var-get mint-price))
(define-read-only (get-token-by-index (nftIndex uint))
(ok (get-all-data nftIndex))
)
(define-read-only (get-beneficiaries (nftIndex uint))
(let
(
(beneficiaries (map-get? nft-beneficiaries {nft-index: nftIndex}))
)
(ok beneficiaries)
)
)
(define-read-only (get-offer-at-index (nftIndex uint) (offerIndex uint))
(let
(
(the-offer (map-get? nft-offer-history {nft-index: nftIndex, offer-index: offerIndex}))
)
(ok the-offer)
)
)
(define-read-only (get-bid-at-index (nftIndex uint) (bidIndex uint))
(let
(
(the-bid (map-get? nft-bid-history {nft-index: nftIndex, bid-index: bidIndex}))
)
(ok the-bid)
)
)
;; Get the edition from a knowledge of the #1 edition and the specific edition number
(define-read-only (get-edition-by-hash (asset-hash (buff 32)) (edition uint))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: edition})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-token-by-hash (asset-hash (buff 32)))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: u1})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-contract-data)
(let
(
(the-administrator (var-get administrator))
(the-mint-price (var-get mint-price))
(the-base-token-uri (var-get base-token-uri))
(the-mint-counter (var-get mint-counter))
(the-platform-fee (var-get platform-fee))
(the-token-name token-name)
(the-token-symbol token-symbol)
)
(ok (tuple (administrator the-administrator)
(mintPrice the-mint-price)
(baseTokenUri the-base-token-uri)
(mintCounter the-mint-counter)
(platformFee the-platform-fee)
(tokenName the-token-name)
(tokenSymbol the-token-symbol)))
)
)
(define-private (get-all-data (nftIndex uint))
(let
(
(the-owner (unwrap-panic (nft-get-owner? my-nft nftIndex)))
(the-token-info (map-get? nft-data {nft-index: nftIndex}))
(the-sale-data (map-get? nft-sale-data {nft-index: nftIndex}))
(the-beneficiary-data (map-get? nft-beneficiaries {nft-index: nftIndex}))
(the-edition-counter (default-to u0 (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex}))))
(the-offer-counter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nftIndex}))))
(the-high-bid-counter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
(ok (tuple (offerCounter the-offer-counter)
(bidCounter the-high-bid-counter)
(editionCounter the-edition-counter)
(nftIndex nftIndex)
(tokenInfo the-token-info)
(saleData the-sale-data)
(beneficiaryData the-beneficiary-data)
(owner the-owner)
)
)
)
)
(define-read-only (get-sale-data (nftIndex uint))
(match (map-get? nft-sale-data {nft-index: nftIndex})
mySaleData
(ok mySaleData)
not-found
)
)
(define-read-only (get-token-name)
(ok token-name)
)
(define-read-only (get-token-symbol)
(ok token-symbol)
)
(define-read-only (get-balance)
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(ok (stx-get-balance (as-contract tx-sender)))
)
)
;; private methods
;; ---------------
(define-private (refund-bid (nftIndex uint) (currentBidder principal) (currentAmount uint))
(begin
(unwrap! (as-contract (stx-transfer? currentAmount tx-sender currentBidder)) failed-to-stx-transfer)
(print {evt: "refund-bid", nftIndex: nftIndex, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok true)
)
)
;; need to account for reserve-stx
(define-private (record-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
;; see place-bid for the payment - no need for this (unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {evt: "record-bid", nftIndex: nftIndex, txSender: tx-sender, bidAmount: bidAmount, bidCounter: bidCounter, appTimestamp: appTimestamp, saleCycle: saleCycle})
(ok true)
)
)
(define-private (next-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {appTimestamp: appTimestamp, bidAmount: bidAmount, bidCounter: bidCounter, evt: "next-bid", nftIndex: nftIndex, saleCycle: saleCycle, txSender: tx-sender})
(ok true)
)
)
;; sends payments to each recipient listed in the royalties
;; Note this is called by mint-edition where thee nftIndex actuallt referes to the series orginal and is where the royalties are stored.
(define-private (payment-split (nftIndex uint) (saleAmount uint) (payer principal))
(let
(
(addresses (unwrap! (get addresses (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(shares (unwrap! (get shares (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(split u0)
;; If secondary sale (sale-cycle > 1) - the seller gets half the sale value and each royalty payment is half the original amount
(scalor (if (> (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set) u1)
percentage-on-secondary u1))
)
(if (is-eq scalor percentage-on-secondary)
;; If secondary sale - pay the seller then split the royalties
(unwrap! (stx-transfer? (/ (* saleAmount (- u100 percentage-on-secondary)) u100) payer (unwrap! (nft-get-owner? my-nft nftIndex) payment-share-error)) transfer-error)
;; Primary sale - split the royalties
true
)
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u0) payment-address-error) (unwrap! (element-at shares u0) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u1) payment-address-error) (unwrap! (element-at shares u1) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u2) payment-address-error) (unwrap! (element-at shares u2) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u3) payment-address-error) (unwrap! (element-at shares u3) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u4) payment-address-error) (unwrap! (element-at shares u4) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u5) payment-address-error) (unwrap! (element-at shares u5) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u6) payment-address-error) (unwrap! (element-at shares u6) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u7) payment-address-error) (unwrap! (element-at shares u7) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u8) payment-address-error) (unwrap! (element-at shares u8) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u9) payment-address-error) (unwrap! (element-at shares u9) payment-share-error)) payment-share-error))
(print {evt: "payment-split", nftIndex: nftIndex, scalor: scalor, payer: payer, saleAmount: saleAmount, seller: (/ (* saleAmount (- u100 percentage-on-secondary)) u100), txSender: tx-sender})
(ok split)
)
)
;; unit of saleAmount is in Satoshi and the share variable is a percentage (ex for 5% it will be equal to 5)
;; also the scalor is 1 on first purchase - direct from artist and 2 for secondary sales - so the seller gets half the
;; sale value and each royalty address gets half their original amount.
(define-private (pay-royalty (scalor uint) (payer principal) (saleAmount uint) (payee principal) (share uint))
(begin
(if (> share u0)
(let
(
(split (/ (* saleAmount (/ share scalor)) percentage-with-twodp))
)
;; ignore royalty payment if its to the buyer / tx-sender.
(if (not (is-eq tx-sender payee))
(unwrap! (stx-transfer? split payer payee) transfer-error)
(unwrap! (ok true) transfer-error)
)
(print {evt: "pay-royalty-primary", payee: payee, payer: payer, saleAmount: saleAmount, scalor: scalor, share: share, split: split, txSender: tx-sender})
(ok split)
)
(ok u0)
)
)
)
| 0x7fda9151a5749a1c2e763ed773002ac5b46186ae09e8e3c523541fcae20c9a66 | 15,309 | success |
bitcoin-lib | ;; Bitcoin parsing library for Clarity
;; provides merkle proof parsing & verification, btc block header parsing, btc tx parsing & more
;; Error codes
(define-constant ERR-OUT-OF-BOUNDS u1)
(define-constant ERR-TOO-MANY-TXINS u2)
(define-constant ERR-TOO-MANY-TXOUTS u3)
(define-constant ERR-VARSLICE-TOO-LONG u4)
(define-constant ERR-BAD-HEADER u5)
(define-constant ERR-PROOF-TOO-SHORT u6)
;; lookup table for converting 1-byte buffers to uints via index-of
(define-constant BUFF_TO_BYTE (list
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f
0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f
0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f
0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a 0x3b 0x3c 0x3d 0x3e 0x3f
0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f
0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f
0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e 0x6f
0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b 0x7c 0x7d 0x7e 0x7f
0x80 0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f
0x90 0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f
0xa0 0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf
0xb0 0xb1 0xb2 0xb3 0xb4 0xb5 0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf
0xc0 0xc1 0xc2 0xc3 0xc4 0xc5 0xc6 0xc7 0xc8 0xc9 0xca 0xcb 0xcc 0xcd 0xce 0xcf
0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf
0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef
0xf0 0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff
))
;; List with 512 items, used for folding something 512 times
(define-constant LIST_512 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 256 items, used for folding something 256 times
(define-constant LIST_256 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 128 items, used for folding something 128 times
(define-constant LIST_128 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 64 items, used for folding something 64 times
(define-constant LIST_64 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 32 items, used for folding something 32 times
(define-constant LIST_32 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 16 items, used for folding something 16 times
(define-constant LIST_16 (list
true true true true true true true true true true true true true true true true
))
;; Convert a 1-byte buff into a uint.
(define-read-only (buff-to-u8 (byte (buff 1)))
(unwrap-panic (index-of BUFF_TO_BYTE byte)))
;; Append a byte at the given index in the given data to acc.
(define-read-only (inner-read-slice-1024 (ignored bool) (input { acc: (buff 1024), data: (buff 1024), index: uint }))
(let (
(acc (get acc input))
(data (get data input))
(ctr (get index input))
(byte (unwrap-panic (element-at data ctr)))
)
{
acc: (unwrap-panic (as-max-len? (concat acc byte) u1024)),
data: data,
index: (+ u1 ctr)
})
)
;; Read 512 bytes from data, starting at index. Return the 512-byte slice.
(define-read-only (read-slice-512 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_512 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 256 bytes from data, starting at index. Return the 256-byte slice.
(define-read-only (read-slice-256 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_256 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 128 bytes from data, starting at index. Return the 128-byte slice.
(define-read-only (read-slice-128 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_128 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 64 bytes from data, starting at index. Return the 64-byte slice.
(define-read-only (read-slice-64 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_64 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 32 bytes from data, starting at index. Return the 32-byte slice.
(define-read-only (read-slice-32 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_32 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 16 bytes from data, starting at index. Return the 16-byte slice.
(define-read-only (read-slice-16 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_16 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 8 bytes from data, starting at index. Return the 8-byte slice.
(define-read-only (read-slice-8 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 (list true true true true true true true true) { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 4 bytes from data, starting at index. Return the 4-byte slice.
(define-read-only (read-slice-4 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 (list true true true true) { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 2 bytes from data, starting at index. Return the 2-byte slice.
(define-read-only (read-slice-2 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 (list true true) { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 1 byte from data, starting at index. Return the 1-byte slice.
(define-read-only (read-slice-1 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 (list true) { acc: 0x, data: (get data input), index: (get index input) })))
;; Read a fixed-sized chunk of data from a given buffer (up to remaining bytes), starting at index, and append it to acc.
;; chunk_size must be a power of 2, up to 1024
(define-read-only (inner-read-slice (chunk_size uint) (input { acc: (buff 1024), buffer: (buff 1024), index: uint, remaining: uint }))
(let (
(ctr (get index input))
(remaining (get remaining input))
)
(if (is-eq u0 remaining)
;; done reading
input
(let (
(acc (get acc input))
(databuff (get buffer input))
)
(if (> chunk_size remaining)
;; chunk size too big for remainder, so just skip it.
input
;; we have at least chunk_size bytes to read!
;; dispatch to the right fixed-size slice reader.
(if (is-eq chunk_size u512)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-512 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u256)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-256 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u128)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-128 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u64)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-64 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u32)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-32 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u16)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-16 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u8)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-8 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u4)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-4 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u2)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-2 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u1)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-1 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
{ acc: acc, buffer: databuff, index: ctr, remaining: remaining }
))))))))))
))
))
)
;; Top-level function to read a slice of a given size from a given (buff 1024), starting at a given offset.
;; Returns (ok (buff 1024)) on success, and it contains "buff[offset..(offset+size)]"
;; Returns (err ERR-OUT-OF-BOUNDS) if the slice offset and/or size would copy a range of bytes outside the given buffer.
(define-read-only (read-slice (data (buff 1024)) (offset uint) (size uint))
(if (or (>= offset (len data)) (> (+ offset size) (len data)))
(err ERR-OUT-OF-BOUNDS)
(begin
(print "read slice")
(print size)
(ok
(get acc
(fold inner-read-slice (list u512 u256 u128 u64 u32 u16 u8 u4 u2 u1) { acc: 0x, buffer: data, index: offset, remaining: size }))
)
)
)
)
;; Reads the next two bytes from txbuff as a big-endian 16-bit integer, and updates the index.
;; Returns (ok { uint16: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff
(define-read-only (read-uint16 (ctx { txbuff: (buff 1024), index: uint }))
(let (
(data (get txbuff ctx))
(base (get index ctx))
(byte-1 (buff-to-u8 (unwrap! (element-at data base) (err ERR-OUT-OF-BOUNDS))))
(byte-2 (buff-to-u8 (unwrap! (element-at data (+ u1 base)) (err ERR-OUT-OF-BOUNDS))))
(ret (+ (* byte-2 u256) byte-1))
)
(begin
(print "read uint16")
(print ret)
(ok {
uint16: ret,
ctx: { txbuff: data, index: (+ u2 base) }
})
))
)
;; Reads the next four bytes from txbuff as a big-endian 32-bit integer, and updates the index.
;; Returns (ok { uint32: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff
(define-read-only (read-uint32 (ctx { txbuff: (buff 1024), index: uint }))
(let (
(data (get txbuff ctx))
(base (get index ctx))
(byte-1 (buff-to-u8 (unwrap! (element-at data base) (err ERR-OUT-OF-BOUNDS))))
(byte-2 (buff-to-u8 (unwrap! (element-at data (+ u1 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-3 (buff-to-u8 (unwrap! (element-at data (+ u2 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-4 (buff-to-u8 (unwrap! (element-at data (+ u3 base)) (err ERR-OUT-OF-BOUNDS))))
(ret (+ (* byte-4 u16777216) (* byte-3 u65536) (* byte-2 u256) byte-1))
)
(begin
(print "read uint32")
(print ret)
(ok {
uint32: ret,
ctx: { txbuff: data, index: (+ u4 base) }
})
))
)
;; Reads the next eight bytes from txbuff as a big-endian 64-bit integer, and updates the index.
;; Returns (ok { uint64: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff
(define-read-only (read-uint64 (ctx { txbuff: (buff 1024), index: uint }))
(let (
(data (get txbuff ctx))
(base (get index ctx))
(byte-1 (buff-to-u8 (unwrap! (element-at data base) (err ERR-OUT-OF-BOUNDS))))
(byte-2 (buff-to-u8 (unwrap! (element-at data (+ u1 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-3 (buff-to-u8 (unwrap! (element-at data (+ u2 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-4 (buff-to-u8 (unwrap! (element-at data (+ u3 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-5 (buff-to-u8 (unwrap! (element-at data (+ u4 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-6 (buff-to-u8 (unwrap! (element-at data (+ u5 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-7 (buff-to-u8 (unwrap! (element-at data (+ u6 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-8 (buff-to-u8 (unwrap! (element-at data (+ u7 base)) (err ERR-OUT-OF-BOUNDS))))
(ret (+
(* byte-8 u72057594037927936)
(* byte-7 u281474976710656)
(* byte-6 u1099511627776)
(* byte-5 u4294967296)
(* byte-4 u16777216)
(* byte-3 u65536)
(* byte-2 u256)
byte-1))
)
(begin
(print "read uint64")
(print ret)
(ok {
uint64: ret,
ctx: { txbuff: data, index: (+ u8 base) }
})
))
)
;; Reads the next varint from txbuff, and updates the index.
;; Returns (ok { varint: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
(define-read-only (read-varint (ctx { txbuff: (buff 1024), index: uint }))
(let (
(ptr (get index ctx))
(tx (get txbuff ctx))
(byte (buff-to-u8 (unwrap! (element-at tx ptr)
(err ERR-OUT-OF-BOUNDS))))
)
(if (<= byte u252)
(begin
(print "varint 1")
(print byte)
;; given byte is the varint
(ok { varint: byte, ctx: { txbuff: tx, index: (+ u1 ptr) }})
)
(if (is-eq byte u253)
(let (
;; next two bytes is the varint
(parsed-u16 (try! (read-uint16 { txbuff: tx, index: (+ u1 ptr) })))
)
(begin
(print "varint 2")
(print (get uint16 parsed-u16))
(ok { varint: (get uint16 parsed-u16), ctx: (get ctx parsed-u16) })
))
(if (is-eq byte u254)
(let (
;; next four bytes is the varint
(parsed-u32 (try! (read-uint32 { txbuff: tx, index: (+ u1 ptr) })))
)
(begin
(print "varint 4")
(print (get uint32 parsed-u32))
(ok { varint: (get uint32 parsed-u32), ctx: (get ctx parsed-u32) })
))
(let (
;; next eight bytes is the varint
(parsed-u64 (try! (read-uint64 { txbuff: tx, index: (+ u1 ptr) })))
)
(begin
(print "varint 8")
(print (get uint64 parsed-u64))
(ok { varint: (get uint64 parsed-u64), ctx: (get ctx parsed-u64) })
))
)
)
))
)
;; Reads a varint-prefixed byte slice from txbuff, and updates the index to point to the byte after the varint and slice.
;; Returns (ok { varslice: (buff 1024), ctx: { txbuff: (buff 1024), index: uint } }) on success, where varslice has the length of the varint prefix.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
(define-read-only (read-varslice (old-ctx { txbuff: (buff 1024), index: uint }))
(let (
(parsed (try! (read-varint old-ctx)))
(slice-len (get varint parsed))
(ctx (get ctx parsed))
(slice (try! (read-slice (get txbuff ctx) (get index ctx) slice-len)))
)
(ok {
varslice: slice,
ctx: { txbuff: (get txbuff ctx), index: (+ (len slice) (get index ctx)) }
}))
)
;; Generate a permutation of a given 32-byte buffer, appending the element at target-index to hash-output.
;; The target-index decides which index in hash-input gets appended to hash-output.
(define-read-only (inner-buff32-permutation (target-index uint) (state { hash-input: (buff 32), hash-output: (buff 32) }))
{
hash-input: (get hash-input state),
hash-output: (unwrap-panic
(as-max-len? (concat
(get hash-output state)
(unwrap-panic
(as-max-len?
(unwrap-panic
(element-at (get hash-input state) target-index))
u32)))
u32))
}
)
;; Reverse the byte order of a 32-byte buffer. Returns the (buff 32).
(define-read-only (reverse-buff32 (input (buff 32)))
(get hash-output
(fold inner-buff32-permutation
(list u31 u30 u29 u28 u27 u26 u25 u24 u23 u22 u21 u20 u19 u18 u17 u16 u15 u14 u13 u12 u11 u10 u9 u8 u7 u6 u5 u4 u3 u2 u1 u0)
{ hash-input: input, hash-output: 0x }))
)
;; Reads a big-endian hash -- consume the next 32 bytes, and reverse them.
;; Returns (ok { hashslice: (buff 32), ctx: { txbuff: (buff 1024), index: uint } }) on success, and updates the index.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
(define-read-only (read-hashslice (old-ctx { txbuff: (buff 1024), index: uint }))
(let (
(hash-le (unwrap-panic
(as-max-len? (try!
(read-slice (get txbuff old-ctx) (get index old-ctx) u32))
u32)))
)
(ok {
hashslice: (reverse-buff32 hash-le),
ctx: { txbuff: (get txbuff old-ctx), index: (+ u32 (get index old-ctx)) }
}))
)
;; Inner fold method to read the next tx input from txbuff.
;; The index in ctx will be updated to point to the next tx input if all goes well (or to the start of the outputs)
;; Returns (ok { ... }) on success.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptSig that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXINS) if there are more than eight inputs to read.
(define-read-only (read-next-txin (ignored bool)
(state-res (response {
ctx: { txbuff: (buff 1024), index: uint },
remaining: uint,
txins: (list 8 {
outpoint: {
hash: (buff 32),
index: uint
},
scriptSig: (buff 256), ;; just big enough to hold a 2-of-3 multisig script
sequence: uint
})
} uint)))
(match state-res
state
(if (< u0 (get remaining state))
(let (
(remaining (get remaining state))
(ctx (get ctx state))
(parsed-hash (try! (read-hashslice ctx)))
(parsed-index (try! (read-uint32 (get ctx parsed-hash))))
(parsed-scriptSig (try! (read-varslice (get ctx parsed-index))))
(parsed-sequence (try! (read-uint32 (get ctx parsed-scriptSig))))
(new-ctx (get ctx parsed-sequence))
)
(ok {
ctx: new-ctx,
remaining: (- remaining u1),
txins: (unwrap!
(as-max-len?
(append (get txins state)
{
outpoint: {
hash: (get hashslice parsed-hash),
index: (get uint32 parsed-index)
},
scriptSig: (unwrap! (as-max-len? (get varslice parsed-scriptSig) u256) (err ERR-VARSLICE-TOO-LONG)),
sequence: (get uint32 parsed-sequence)
})
u8)
(err ERR-TOO-MANY-TXINS))
}))
(ok state)
)
error
(err error)
)
)
;; Read a transaction's inputs.
;; Returns (ok { txins: (list { ... }), remaining: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success, and updates the index in ctx to point to the start of the tx outputs.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptSig that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXINS) if there are more than eight inputs to read.
(define-read-only (read-txins (ctx { txbuff: (buff 1024), index: uint }))
(let (
(parsed-num-txins (try! (read-varint ctx)))
(num-txins (get varint parsed-num-txins))
(new-ctx (get ctx parsed-num-txins))
)
(if (> num-txins u8)
(err ERR-TOO-MANY-TXINS)
(fold read-next-txin (list true true true true true true true true) (ok { ctx: new-ctx, remaining: num-txins, txins: (list ) }))
))
)
;; Read the next transaction output, and update the index in ctx to point to the next output.
;; Returns (ok { ... }) on success
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptPubKey that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXOUTS) if there are more than eight outputs to read.
(define-read-only (read-next-txout (ignored bool)
(state-res (response {
ctx: { txbuff: (buff 1024), index: uint },
remaining: uint,
txouts: (list 8 {
value: uint,
scriptPubKey: (buff 128)
})
} uint)))
(match state-res
state
(if (< u0 (get remaining state))
(let (
(remaining (get remaining state))
(parsed-value (try! (read-uint64 (get ctx state))))
(parsed-script (try! (read-varslice (get ctx parsed-value))))
(new-ctx (get ctx parsed-script))
)
(ok {
ctx: new-ctx,
remaining: (- remaining u1),
txouts: (unwrap!
(as-max-len?
(append (get txouts state)
{
value: (get uint64 parsed-value),
scriptPubKey: (unwrap! (as-max-len? (get varslice parsed-script) u128) (err ERR-VARSLICE-TOO-LONG))
})
u8)
(err ERR-TOO-MANY-TXOUTS))
}))
(ok state)
)
error
(err error)
)
)
;; Read all transaction outputs in a transaction. Update the index to point to the first byte after the outputs, if all goes well.
;; Returns (ok { txouts: (list { ... }), remaining: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success, and updates the index in ctx to point to the start of the tx outputs.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptPubKey that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXOUTS) if there are more than eight outputs to read.
(define-read-only (read-txouts (ctx { txbuff: (buff 1024), index: uint }))
(let (
(parsed-num-txouts (try! (read-varint ctx)))
(num-txouts (get varint parsed-num-txouts))
(new-ctx (get ctx parsed-num-txouts))
)
(if (> num-txouts u8)
(err ERR-TOO-MANY-TXOUTS)
(fold read-next-txout (list true true true true true true true true) (ok { ctx: new-ctx, remaining: num-txouts, txouts: (list ) }))
))
)
;; Parse a Bitcoin transaction, with up to 8 inputs and 8 outputs, with scriptSigs of up to 256 bytes each, and with scriptPubKeys up to 128 bytes.
;; Returns a tuple structured as follows on success:
;; (ok {
;; version: uint, ;; tx version
;; ins: (list 8
;; {
;; outpoint: { ;; pointer to the utxo this input consumes
;; hash: (buff 32),
;; index: uint
;; },
;; scriptSig: (buff 256), ;; spending condition script
;; sequence: uint
;; }),
;; outs: (list 8
;; {
;; value: uint, ;; satoshis sent
;; scriptPubKey: (buff 128) ;; parse this to get an address
;; }),
;; locktime: uint
;; })
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptPubKey or scriptSig that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXOUTS) if there are more than eight inputs to read.
;; Returns (err ERR-TOO-MANY-TXINS) if there are more than eight outputs to read.
(define-read-only (parse-tx (tx (buff 1024)))
(let (
(ctx { txbuff: tx, index: u0 })
(parsed-version (try! (read-uint32 ctx)))
(parsed-txins (try! (read-txins (get ctx parsed-version))))
(parsed-txouts (try! (read-txouts (get ctx parsed-txins))))
(parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))
)
(ok {
version: (get uint32 parsed-version),
ins: (get txins parsed-txins),
outs: (get txouts parsed-txouts),
locktime: (get uint32 parsed-locktime)
}))
)
;; Parse a Bitcoin block header.
;; Returns a tuple structured as folowed on success:
;; (ok {
;; version: uint, ;; block version,
;; parent: (buff 32), ;; parent block hash,
;; merkle-root: (buff 32), ;; merkle root for all this block's transactions
;; timestamp: uint, ;; UNIX epoch timestamp of this block, in seconds
;; nbits: uint, ;; compact block difficulty representation
;; nonce: uint ;; PoW solution
;; })
;; Returns (err ERR-BAD-HEADER) if the header buffer isn't actually 80 bytes long.
(define-read-only (parse-block-header (headerbuff (buff 80)))
(let (
(ctx { txbuff: (unwrap! (as-max-len? headerbuff u1024) (err ERR-BAD-HEADER)), index: u0 })
;; none of these should fail, since they're all fixed-length fields whose lengths sum to 80
(parsed-version (unwrap-panic (read-uint32 ctx)))
(parsed-parent-hash (unwrap-panic (read-hashslice (get ctx parsed-version))))
(parsed-merkle-root (unwrap-panic (read-hashslice (get ctx parsed-parent-hash))))
(parsed-timestamp (unwrap-panic (read-uint32 (get ctx parsed-merkle-root))))
(parsed-nbits (unwrap-panic (read-uint32 (get ctx parsed-timestamp))))
(parsed-nonce (unwrap-panic (read-uint32 (get ctx parsed-nbits))))
)
(ok {
version: (get uint32 parsed-version),
parent: (get hashslice parsed-parent-hash),
merkle-root: (get hashslice parsed-merkle-root),
timestamp: (get uint32 parsed-timestamp),
nbits: (get uint32 parsed-nbits),
nonce: (get uint32 parsed-nonce)
}))
)
;; Verify that a block header hashes to a burnchain header hash at a given height.
;; Returns true if so; false if not.
(define-read-only (verify-block-header (headerbuff (buff 80)) (expected-block-height uint))
(match (get-block-info? burnchain-header-hash expected-block-height)
bhh (is-eq bhh (reverse-buff32 (sha256 (sha256 headerbuff))))
false
)
)
;; Get the txid of a transaction, but big-endian.
;; This is the reverse of what you see on block explorers.
(define-read-only (get-reversed-txid (tx (buff 1024)))
(sha256 (sha256 tx)))
;; Get the txid of a transaction.
;; This is what you see on block explorers.
(define-read-only (get-txid (tx (buff 1024)))
(reverse-buff32 (get-reversed-txid tx))
)
;; Determine if the ith bit in a uint is set to 1
(define-read-only (is-bit-set (val uint) (bit uint))
(is-eq (mod (/ val (pow u2 bit)) u2) u1)
)
;; Verify the next step of a Merkle proof.
;; This hashes cur-hash against the ctr-th hash in proof-hashes, and uses that as the next cur-hash.
;; The path is a bitfield describing the walk from the txid up to the merkle root:
;; * if the ith bit is 0, then cur-hash is hashed before the next proof-hash (cur-hash is "left").
;; * if the ith bit is 1, then the next proof-hash is hashed before cur-hash (cur-hash is "right").
;; The proof verifies if cur-hash is equal to root-hash, and we're out of proof-hashes to check.
(define-read-only (inner-merkle-proof-verify (ctr uint) (state { path: uint, root-hash: (buff 32), proof-hashes: (list 12 (buff 32)), tree-depth: uint, cur-hash: (buff 32), verified: bool }))
(if (get verified state)
state
(if (>= ctr (get tree-depth state))
(begin
(print "ctr exceeds proof length or tree depth")
(print ctr)
(print (get tree-depth state))
(print (len (get proof-hashes state)))
(merge state { verified: false })
)
(let (
(path (get path state))
(is-left (is-bit-set path ctr))
(proof-hashes (get proof-hashes state))
(cur-hash (get cur-hash state))
(root-hash (get root-hash state))
(h1 (if is-left (unwrap-panic (element-at proof-hashes ctr)) cur-hash))
(h2 (if is-left cur-hash (unwrap-panic (element-at proof-hashes ctr))))
(next-hash (sha256 (sha256 (concat h1 h2))))
(is-verified (and (is-eq (+ u1 ctr) (len proof-hashes)) (is-eq next-hash root-hash)))
)
(begin
(print "cur-hash")
(print cur-hash)
(print "next-hash")
(print h1)
(print h2)
(print next-hash)
(merge state { cur-hash: next-hash, verified: is-verified })
))
)
)
)
;; Verify a Merkle proof, given the _reversed_ txid of a transaction, the merkle root of its block, and a proof consisting of:
;; * The index in the block where the transaction can be found (starting from 0),
;; * The list of hashes that link the txid to the merkle root,
;; * The depth of the block's merkle tree (required because Bitcoin does not identify merkle tree nodes as being leaves or intermediates).
;; The _reversed_ txid is required because that's the order (big-endian) processes them in.
;; The tx-index is required because it tells us the left/right traversals we'd make if we were walking down the tree from root to transaction,
;; and is thus used to deduce the order in which to hash the intermediate hashes with one another to link the txid to the merkle root.
;; Returns (ok true) if the proof is valid.
;; Returns (ok false) if the proof is invalid.
;; Returns (err ERR-PROOF-TOO-SHORT) if the proof's hashes aren't long enough to link the txid to the merkle root.
(define-read-only (verify-merkle-proof (reversed-txid (buff 32)) (merkle-root (buff 32)) (proof { tx-index: uint, hashes: (list 12 (buff 32)), tree-depth: uint }))
(if (> (get tree-depth proof) (len (get hashes proof)))
(err ERR-PROOF-TOO-SHORT)
(ok
(get verified
(fold inner-merkle-proof-verify
(list u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11)
{ path: (+ (pow u2 (get tree-depth proof)) (get tx-index proof)), root-hash: merkle-root, proof-hashes: (get hashes proof), cur-hash: reversed-txid, tree-depth: (get tree-depth proof), verified: false }))
)
)
)
;; Top-level verification code to determine whether or not a Bitcoin transaction was mined in a prior Bitcoin block.
;; It takes the block header and block height, the transaction, and a merkle proof, and determines that:
;; * the block header corresponds to the block that was mined at the given Bitcoin height
;; * the transaction's merkle proof links it to the block header's merkle root.
;; The proof is a list of sibling merkle tree nodes that allow us to calculate the parent node from two children nodes in each merkle tree level,
;; the depth of the block's merkle tree, and the index in the block in which the given transaction can be found (starting from 0).
;; The first element in hashes must be the given transaction's sibling transaction's ID. This and the given transaction's txid are hashed to
;; calculate the parent hash in the merkle tree, which is then hashed with the *next* hash in the proof, and so on and so forth, until the final
;; hash can be compared against the block header's merkle root field. The tx-index tells us in which order to hash each pair of siblings.
;; Note that the proof hashes -- including the sibling txid -- must be _big-endian_ hashes, because this is how Bitcoin generates them.
;; This is the reverse of what you'd see in a block explorer!
;; Returns (ok true) if the proof checks out.
;; Returns (ok false) if not.
;; Returns (err ERR-PROOF-TOO-SHORT) if the proof doesn't contain enough intermediate hash nodes in the merkle tree.
(define-read-only (was-tx-mined? (block { header: (buff 80), height: uint }) (tx (buff 1024)) (proof { tx-index: uint, hashes: (list 12 (buff 32)), tree-depth: uint }))
(if (verify-block-header (get header block) (get height block))
(verify-merkle-proof (get-reversed-txid tx) (get merkle-root (try! (parse-block-header (get header block)))) proof)
(ok false)
)
)
| 0xedd750c5771559cb784481ccd014aea91fb0ce019dc54816b5ea51794549eec2 | 15,333 | success |
bitcoin-lib | ;; Bitcoin parsing library for Clarity
;; provides merkle proof parsing & verification, btc block header parsing, btc tx parsing & more
;; Error codes
(define-constant ERR-OUT-OF-BOUNDS u1)
(define-constant ERR-TOO-MANY-TXINS u2)
(define-constant ERR-TOO-MANY-TXOUTS u3)
(define-constant ERR-VARSLICE-TOO-LONG u4)
(define-constant ERR-BAD-HEADER u5)
(define-constant ERR-PROOF-TOO-SHORT u6)
;; lookup table for converting 1-byte buffers to uints via index-of
(define-constant BUFF_TO_BYTE (list
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f
0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f
0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f
0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a 0x3b 0x3c 0x3d 0x3e 0x3f
0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f
0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f
0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e 0x6f
0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b 0x7c 0x7d 0x7e 0x7f
0x80 0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f
0x90 0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f
0xa0 0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf
0xb0 0xb1 0xb2 0xb3 0xb4 0xb5 0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf
0xc0 0xc1 0xc2 0xc3 0xc4 0xc5 0xc6 0xc7 0xc8 0xc9 0xca 0xcb 0xcc 0xcd 0xce 0xcf
0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf
0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef
0xf0 0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff
))
;; List with 512 items, used for folding something 512 times
(define-constant LIST_512 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 256 items, used for folding something 256 times
(define-constant LIST_256 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 128 items, used for folding something 128 times
(define-constant LIST_128 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 64 items, used for folding something 64 times
(define-constant LIST_64 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 32 items, used for folding something 32 times
(define-constant LIST_32 (list
true true true true true true true true true true true true true true true true
true true true true true true true true true true true true true true true true
))
;; List with 16 items, used for folding something 16 times
(define-constant LIST_16 (list
true true true true true true true true true true true true true true true true
))
;; Convert a 1-byte buff into a uint.
(define-read-only (buff-to-u8 (byte (buff 1)))
(unwrap-panic (index-of BUFF_TO_BYTE byte)))
;; Append a byte at the given index in the given data to acc.
(define-read-only (inner-read-slice-1024 (ignored bool) (input { acc: (buff 1024), data: (buff 1024), index: uint }))
(let (
(acc (get acc input))
(data (get data input))
(ctr (get index input))
(byte (unwrap-panic (element-at data ctr)))
)
{
acc: (unwrap-panic (as-max-len? (concat acc byte) u1024)),
data: data,
index: (+ u1 ctr)
})
)
;; Read 512 bytes from data, starting at index. Return the 512-byte slice.
(define-read-only (read-slice-512 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_512 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 256 bytes from data, starting at index. Return the 256-byte slice.
(define-read-only (read-slice-256 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_256 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 128 bytes from data, starting at index. Return the 128-byte slice.
(define-read-only (read-slice-128 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_128 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 64 bytes from data, starting at index. Return the 64-byte slice.
(define-read-only (read-slice-64 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_64 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 32 bytes from data, starting at index. Return the 32-byte slice.
(define-read-only (read-slice-32 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_32 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 16 bytes from data, starting at index. Return the 16-byte slice.
(define-read-only (read-slice-16 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 LIST_16 { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 8 bytes from data, starting at index. Return the 8-byte slice.
(define-read-only (read-slice-8 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 (list true true true true true true true true) { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 4 bytes from data, starting at index. Return the 4-byte slice.
(define-read-only (read-slice-4 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 (list true true true true) { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 2 bytes from data, starting at index. Return the 2-byte slice.
(define-read-only (read-slice-2 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 (list true true) { acc: 0x, data: (get data input), index: (get index input) })))
;; Read 1 byte from data, starting at index. Return the 1-byte slice.
(define-read-only (read-slice-1 (input { data: (buff 1024), index: uint }))
(get acc
(fold inner-read-slice-1024 (list true) { acc: 0x, data: (get data input), index: (get index input) })))
;; Read a fixed-sized chunk of data from a given buffer (up to remaining bytes), starting at index, and append it to acc.
;; chunk_size must be a power of 2, up to 1024
(define-read-only (inner-read-slice (chunk_size uint) (input { acc: (buff 1024), buffer: (buff 1024), index: uint, remaining: uint }))
(let (
(ctr (get index input))
(remaining (get remaining input))
)
(if (is-eq u0 remaining)
;; done reading
input
(let (
(acc (get acc input))
(databuff (get buffer input))
)
(if (> chunk_size remaining)
;; chunk size too big for remainder, so just skip it.
input
;; we have at least chunk_size bytes to read!
;; dispatch to the right fixed-size slice reader.
(if (is-eq chunk_size u512)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-512 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u256)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-256 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u128)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-128 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u64)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-64 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u32)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-32 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u16)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-16 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u8)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-8 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u4)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-4 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u2)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-2 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
(if (is-eq chunk_size u1)
{ acc: (unwrap-panic (as-max-len? (concat acc (read-slice-1 { data: databuff, index: ctr })) u1024)), buffer: databuff, index: (+ chunk_size ctr), remaining: (- remaining chunk_size) }
{ acc: acc, buffer: databuff, index: ctr, remaining: remaining }
))))))))))
))
))
)
;; Top-level function to read a slice of a given size from a given (buff 1024), starting at a given offset.
;; Returns (ok (buff 1024)) on success, and it contains "buff[offset..(offset+size)]"
;; Returns (err ERR-OUT-OF-BOUNDS) if the slice offset and/or size would copy a range of bytes outside the given buffer.
(define-read-only (read-slice (data (buff 1024)) (offset uint) (size uint))
(if (or (>= offset (len data)) (> (+ offset size) (len data)))
(err ERR-OUT-OF-BOUNDS)
(begin
(print "read slice")
(print size)
(ok
(get acc
(fold inner-read-slice (list u512 u256 u128 u64 u32 u16 u8 u4 u2 u1) { acc: 0x, buffer: data, index: offset, remaining: size }))
)
)
)
)
;; Reads the next two bytes from txbuff as a big-endian 16-bit integer, and updates the index.
;; Returns (ok { uint16: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff
(define-read-only (read-uint16 (ctx { txbuff: (buff 1024), index: uint }))
(let (
(data (get txbuff ctx))
(base (get index ctx))
(byte-1 (buff-to-u8 (unwrap! (element-at data base) (err ERR-OUT-OF-BOUNDS))))
(byte-2 (buff-to-u8 (unwrap! (element-at data (+ u1 base)) (err ERR-OUT-OF-BOUNDS))))
(ret (+ (* byte-2 u256) byte-1))
)
(begin
(print "read uint16")
(print ret)
(ok {
uint16: ret,
ctx: { txbuff: data, index: (+ u2 base) }
})
))
)
;; Reads the next four bytes from txbuff as a big-endian 32-bit integer, and updates the index.
;; Returns (ok { uint32: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff
(define-read-only (read-uint32 (ctx { txbuff: (buff 1024), index: uint }))
(let (
(data (get txbuff ctx))
(base (get index ctx))
(byte-1 (buff-to-u8 (unwrap! (element-at data base) (err ERR-OUT-OF-BOUNDS))))
(byte-2 (buff-to-u8 (unwrap! (element-at data (+ u1 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-3 (buff-to-u8 (unwrap! (element-at data (+ u2 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-4 (buff-to-u8 (unwrap! (element-at data (+ u3 base)) (err ERR-OUT-OF-BOUNDS))))
(ret (+ (* byte-4 u16777216) (* byte-3 u65536) (* byte-2 u256) byte-1))
)
(begin
(print "read uint32")
(print ret)
(ok {
uint32: ret,
ctx: { txbuff: data, index: (+ u4 base) }
})
))
)
;; Reads the next eight bytes from txbuff as a big-endian 64-bit integer, and updates the index.
;; Returns (ok { uint64: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff
(define-read-only (read-uint64 (ctx { txbuff: (buff 1024), index: uint }))
(let (
(data (get txbuff ctx))
(base (get index ctx))
(byte-1 (buff-to-u8 (unwrap! (element-at data base) (err ERR-OUT-OF-BOUNDS))))
(byte-2 (buff-to-u8 (unwrap! (element-at data (+ u1 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-3 (buff-to-u8 (unwrap! (element-at data (+ u2 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-4 (buff-to-u8 (unwrap! (element-at data (+ u3 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-5 (buff-to-u8 (unwrap! (element-at data (+ u4 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-6 (buff-to-u8 (unwrap! (element-at data (+ u5 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-7 (buff-to-u8 (unwrap! (element-at data (+ u6 base)) (err ERR-OUT-OF-BOUNDS))))
(byte-8 (buff-to-u8 (unwrap! (element-at data (+ u7 base)) (err ERR-OUT-OF-BOUNDS))))
(ret (+
(* byte-8 u72057594037927936)
(* byte-7 u281474976710656)
(* byte-6 u1099511627776)
(* byte-5 u4294967296)
(* byte-4 u16777216)
(* byte-3 u65536)
(* byte-2 u256)
byte-1))
)
(begin
(print "read uint64")
(print ret)
(ok {
uint64: ret,
ctx: { txbuff: data, index: (+ u8 base) }
})
))
)
;; Reads the next varint from txbuff, and updates the index.
;; Returns (ok { varint: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
(define-read-only (read-varint (ctx { txbuff: (buff 1024), index: uint }))
(let (
(ptr (get index ctx))
(tx (get txbuff ctx))
(byte (buff-to-u8 (unwrap! (element-at tx ptr)
(err ERR-OUT-OF-BOUNDS))))
)
(if (<= byte u252)
(begin
(print "varint 1")
(print byte)
;; given byte is the varint
(ok { varint: byte, ctx: { txbuff: tx, index: (+ u1 ptr) }})
)
(if (is-eq byte u253)
(let (
;; next two bytes is the varint
(parsed-u16 (try! (read-uint16 { txbuff: tx, index: (+ u1 ptr) })))
)
(begin
(print "varint 2")
(print (get uint16 parsed-u16))
(ok { varint: (get uint16 parsed-u16), ctx: (get ctx parsed-u16) })
))
(if (is-eq byte u254)
(let (
;; next four bytes is the varint
(parsed-u32 (try! (read-uint32 { txbuff: tx, index: (+ u1 ptr) })))
)
(begin
(print "varint 4")
(print (get uint32 parsed-u32))
(ok { varint: (get uint32 parsed-u32), ctx: (get ctx parsed-u32) })
))
(let (
;; next eight bytes is the varint
(parsed-u64 (try! (read-uint64 { txbuff: tx, index: (+ u1 ptr) })))
)
(begin
(print "varint 8")
(print (get uint64 parsed-u64))
(ok { varint: (get uint64 parsed-u64), ctx: (get ctx parsed-u64) })
))
)
)
))
)
;; Reads a varint-prefixed byte slice from txbuff, and updates the index to point to the byte after the varint and slice.
;; Returns (ok { varslice: (buff 1024), ctx: { txbuff: (buff 1024), index: uint } }) on success, where varslice has the length of the varint prefix.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
(define-read-only (read-varslice (old-ctx { txbuff: (buff 1024), index: uint }))
(let (
(parsed (try! (read-varint old-ctx)))
(slice-len (get varint parsed))
(ctx (get ctx parsed))
(slice (try! (read-slice (get txbuff ctx) (get index ctx) slice-len)))
)
(ok {
varslice: slice,
ctx: { txbuff: (get txbuff ctx), index: (+ (len slice) (get index ctx)) }
}))
)
;; Generate a permutation of a given 32-byte buffer, appending the element at target-index to hash-output.
;; The target-index decides which index in hash-input gets appended to hash-output.
(define-read-only (inner-buff32-permutation (target-index uint) (state { hash-input: (buff 32), hash-output: (buff 32) }))
{
hash-input: (get hash-input state),
hash-output: (unwrap-panic
(as-max-len? (concat
(get hash-output state)
(unwrap-panic
(as-max-len?
(unwrap-panic
(element-at (get hash-input state) target-index))
u32)))
u32))
}
)
;; Reverse the byte order of a 32-byte buffer. Returns the (buff 32).
(define-read-only (reverse-buff32 (input (buff 32)))
(get hash-output
(fold inner-buff32-permutation
(list u31 u30 u29 u28 u27 u26 u25 u24 u23 u22 u21 u20 u19 u18 u17 u16 u15 u14 u13 u12 u11 u10 u9 u8 u7 u6 u5 u4 u3 u2 u1 u0)
{ hash-input: input, hash-output: 0x }))
)
;; Reads a big-endian hash -- consume the next 32 bytes, and reverse them.
;; Returns (ok { hashslice: (buff 32), ctx: { txbuff: (buff 1024), index: uint } }) on success, and updates the index.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
(define-read-only (read-hashslice (old-ctx { txbuff: (buff 1024), index: uint }))
(let (
(hash-le (unwrap-panic
(as-max-len? (try!
(read-slice (get txbuff old-ctx) (get index old-ctx) u32))
u32)))
)
(ok {
hashslice: (reverse-buff32 hash-le),
ctx: { txbuff: (get txbuff old-ctx), index: (+ u32 (get index old-ctx)) }
}))
)
;; Inner fold method to read the next tx input from txbuff.
;; The index in ctx will be updated to point to the next tx input if all goes well (or to the start of the outputs)
;; Returns (ok { ... }) on success.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptSig that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXINS) if there are more than eight inputs to read.
(define-read-only (read-next-txin (ignored bool)
(state-res (response {
ctx: { txbuff: (buff 1024), index: uint },
remaining: uint,
txins: (list 8 {
outpoint: {
hash: (buff 32),
index: uint
},
scriptSig: (buff 256), ;; just big enough to hold a 2-of-3 multisig script
sequence: uint
})
} uint)))
(match state-res
state
(if (< u0 (get remaining state))
(let (
(remaining (get remaining state))
(ctx (get ctx state))
(parsed-hash (try! (read-hashslice ctx)))
(parsed-index (try! (read-uint32 (get ctx parsed-hash))))
(parsed-scriptSig (try! (read-varslice (get ctx parsed-index))))
(parsed-sequence (try! (read-uint32 (get ctx parsed-scriptSig))))
(new-ctx (get ctx parsed-sequence))
)
(ok {
ctx: new-ctx,
remaining: (- remaining u1),
txins: (unwrap!
(as-max-len?
(append (get txins state)
{
outpoint: {
hash: (get hashslice parsed-hash),
index: (get uint32 parsed-index)
},
scriptSig: (unwrap! (as-max-len? (get varslice parsed-scriptSig) u256) (err ERR-VARSLICE-TOO-LONG)),
sequence: (get uint32 parsed-sequence)
})
u8)
(err ERR-TOO-MANY-TXINS))
}))
(ok state)
)
error
(err error)
)
)
;; Read a transaction's inputs.
;; Returns (ok { txins: (list { ... }), remaining: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success, and updates the index in ctx to point to the start of the tx outputs.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptSig that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXINS) if there are more than eight inputs to read.
(define-read-only (read-txins (ctx { txbuff: (buff 1024), index: uint }))
(let (
(parsed-num-txins (try! (read-varint ctx)))
(num-txins (get varint parsed-num-txins))
(new-ctx (get ctx parsed-num-txins))
)
(if (> num-txins u8)
(err ERR-TOO-MANY-TXINS)
(fold read-next-txin (list true true true true true true true true) (ok { ctx: new-ctx, remaining: num-txins, txins: (list ) }))
))
)
;; Read the next transaction output, and update the index in ctx to point to the next output.
;; Returns (ok { ... }) on success
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptPubKey that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXOUTS) if there are more than eight outputs to read.
(define-read-only (read-next-txout (ignored bool)
(state-res (response {
ctx: { txbuff: (buff 1024), index: uint },
remaining: uint,
txouts: (list 8 {
value: uint,
scriptPubKey: (buff 128)
})
} uint)))
(match state-res
state
(if (< u0 (get remaining state))
(let (
(remaining (get remaining state))
(parsed-value (try! (read-uint64 (get ctx state))))
(parsed-script (try! (read-varslice (get ctx parsed-value))))
(new-ctx (get ctx parsed-script))
)
(ok {
ctx: new-ctx,
remaining: (- remaining u1),
txouts: (unwrap!
(as-max-len?
(append (get txouts state)
{
value: (get uint64 parsed-value),
scriptPubKey: (unwrap! (as-max-len? (get varslice parsed-script) u128) (err ERR-VARSLICE-TOO-LONG))
})
u8)
(err ERR-TOO-MANY-TXOUTS))
}))
(ok state)
)
error
(err error)
)
)
;; Read all transaction outputs in a transaction. Update the index to point to the first byte after the outputs, if all goes well.
;; Returns (ok { txouts: (list { ... }), remaining: uint, ctx: { txbuff: (buff 1024), index: uint } }) on success, and updates the index in ctx to point to the start of the tx outputs.
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptPubKey that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXOUTS) if there are more than eight outputs to read.
(define-read-only (read-txouts (ctx { txbuff: (buff 1024), index: uint }))
(let (
(parsed-num-txouts (try! (read-varint ctx)))
(num-txouts (get varint parsed-num-txouts))
(new-ctx (get ctx parsed-num-txouts))
)
(if (> num-txouts u8)
(err ERR-TOO-MANY-TXOUTS)
(fold read-next-txout (list true true true true true true true true) (ok { ctx: new-ctx, remaining: num-txouts, txouts: (list ) }))
))
)
;; Parse a Bitcoin transaction, with up to 8 inputs and 8 outputs, with scriptSigs of up to 256 bytes each, and with scriptPubKeys up to 128 bytes.
;; Returns a tuple structured as follows on success:
;; (ok {
;; version: uint, ;; tx version
;; ins: (list 8
;; {
;; outpoint: { ;; pointer to the utxo this input consumes
;; hash: (buff 32),
;; index: uint
;; },
;; scriptSig: (buff 256), ;; spending condition script
;; sequence: uint
;; }),
;; outs: (list 8
;; {
;; value: uint, ;; satoshis sent
;; scriptPubKey: (buff 128) ;; parse this to get an address
;; }),
;; locktime: uint
;; })
;; Returns (err ERR-OUT-OF-BOUNDS) if we read past the end of txbuff.
;; Returns (err ERR-VARSLICE-TOO-LONG) if we find a scriptPubKey or scriptSig that's too long to parse.
;; Returns (err ERR-TOO-MANY-TXOUTS) if there are more than eight inputs to read.
;; Returns (err ERR-TOO-MANY-TXINS) if there are more than eight outputs to read.
(define-read-only (parse-tx (tx (buff 1024)))
(let (
(ctx { txbuff: tx, index: u0 })
(parsed-version (try! (read-uint32 ctx)))
(parsed-txins (try! (read-txins (get ctx parsed-version))))
(parsed-txouts (try! (read-txouts (get ctx parsed-txins))))
(parsed-locktime (try! (read-uint32 (get ctx parsed-txouts))))
)
(ok {
version: (get uint32 parsed-version),
ins: (get txins parsed-txins),
outs: (get txouts parsed-txouts),
locktime: (get uint32 parsed-locktime)
}))
)
;; Parse a Bitcoin block header.
;; Returns a tuple structured as folowed on success:
;; (ok {
;; version: uint, ;; block version,
;; parent: (buff 32), ;; parent block hash,
;; merkle-root: (buff 32), ;; merkle root for all this block's transactions
;; timestamp: uint, ;; UNIX epoch timestamp of this block, in seconds
;; nbits: uint, ;; compact block difficulty representation
;; nonce: uint ;; PoW solution
;; })
;; Returns (err ERR-BAD-HEADER) if the header buffer isn't actually 80 bytes long.
(define-read-only (parse-block-header (headerbuff (buff 80)))
(let (
(ctx { txbuff: (unwrap! (as-max-len? headerbuff u1024) (err ERR-BAD-HEADER)), index: u0 })
;; none of these should fail, since they're all fixed-length fields whose lengths sum to 80
(parsed-version (unwrap-panic (read-uint32 ctx)))
(parsed-parent-hash (unwrap-panic (read-hashslice (get ctx parsed-version))))
(parsed-merkle-root (unwrap-panic (read-hashslice (get ctx parsed-parent-hash))))
(parsed-timestamp (unwrap-panic (read-uint32 (get ctx parsed-merkle-root))))
(parsed-nbits (unwrap-panic (read-uint32 (get ctx parsed-timestamp))))
(parsed-nonce (unwrap-panic (read-uint32 (get ctx parsed-nbits))))
)
(ok {
version: (get uint32 parsed-version),
parent: (get hashslice parsed-parent-hash),
merkle-root: (get hashslice parsed-merkle-root),
timestamp: (get uint32 parsed-timestamp),
nbits: (get uint32 parsed-nbits),
nonce: (get uint32 parsed-nonce)
}))
)
;; Verify that a block header hashes to a burnchain header hash at a given height.
;; Returns true if so; false if not.
(define-read-only (verify-block-header (headerbuff (buff 80)) (expected-block-height uint))
(match (get-block-info? burnchain-header-hash expected-block-height)
bhh (is-eq bhh (reverse-buff32 (sha256 (sha256 headerbuff))))
false
)
)
;; Get the txid of a transaction, but big-endian.
;; This is the reverse of what you see on block explorers.
(define-read-only (get-reversed-txid (tx (buff 1024)))
(sha256 (sha256 tx)))
;; Get the txid of a transaction.
;; This is what you see on block explorers.
(define-read-only (get-txid (tx (buff 1024)))
(reverse-buff32 (get-reversed-txid tx))
)
;; Determine if the ith bit in a uint is set to 1
(define-read-only (is-bit-set (val uint) (bit uint))
(is-eq (mod (/ val (pow u2 bit)) u2) u1)
)
;; Verify the next step of a Merkle proof.
;; This hashes cur-hash against the ctr-th hash in proof-hashes, and uses that as the next cur-hash.
;; The path is a bitfield describing the walk from the txid up to the merkle root:
;; * if the ith bit is 0, then cur-hash is hashed before the next proof-hash (cur-hash is "left").
;; * if the ith bit is 1, then the next proof-hash is hashed before cur-hash (cur-hash is "right").
;; The proof verifies if cur-hash is equal to root-hash, and we're out of proof-hashes to check.
(define-read-only (inner-merkle-proof-verify (ctr uint) (state { path: uint, root-hash: (buff 32), proof-hashes: (list 12 (buff 32)), tree-depth: uint, cur-hash: (buff 32), verified: bool }))
(if (get verified state)
state
(if (>= ctr (get tree-depth state))
(begin
(print "ctr exceeds proof length or tree depth")
(print ctr)
(print (get tree-depth state))
(print (len (get proof-hashes state)))
(merge state { verified: false })
)
(let (
(path (get path state))
(is-left (is-bit-set path ctr))
(proof-hashes (get proof-hashes state))
(cur-hash (get cur-hash state))
(root-hash (get root-hash state))
(h1 (if is-left (unwrap-panic (element-at proof-hashes ctr)) cur-hash))
(h2 (if is-left cur-hash (unwrap-panic (element-at proof-hashes ctr))))
(next-hash (sha256 (sha256 (concat h1 h2))))
(is-verified (and (is-eq (+ u1 ctr) (len proof-hashes)) (is-eq next-hash root-hash)))
)
(begin
(print "cur-hash")
(print cur-hash)
(print "next-hash")
(print h1)
(print h2)
(print next-hash)
(merge state { cur-hash: next-hash, verified: is-verified })
))
)
)
)
;; Verify a Merkle proof, given the _reversed_ txid of a transaction, the merkle root of its block, and a proof consisting of:
;; * The index in the block where the transaction can be found (starting from 0),
;; * The list of hashes that link the txid to the merkle root,
;; * The depth of the block's merkle tree (required because Bitcoin does not identify merkle tree nodes as being leaves or intermediates).
;; The _reversed_ txid is required because that's the order (big-endian) processes them in.
;; The tx-index is required because it tells us the left/right traversals we'd make if we were walking down the tree from root to transaction,
;; and is thus used to deduce the order in which to hash the intermediate hashes with one another to link the txid to the merkle root.
;; Returns (ok true) if the proof is valid.
;; Returns (ok false) if the proof is invalid.
;; Returns (err ERR-PROOF-TOO-SHORT) if the proof's hashes aren't long enough to link the txid to the merkle root.
(define-read-only (verify-merkle-proof (reversed-txid (buff 32)) (merkle-root (buff 32)) (proof { tx-index: uint, hashes: (list 12 (buff 32)), tree-depth: uint }))
(if (> (get tree-depth proof) (len (get hashes proof)))
(err ERR-PROOF-TOO-SHORT)
(ok
(get verified
(fold inner-merkle-proof-verify
(list u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11)
{ path: (+ (pow u2 (get tree-depth proof)) (get tx-index proof)), root-hash: merkle-root, proof-hashes: (get hashes proof), cur-hash: reversed-txid, tree-depth: (get tree-depth proof), verified: false }))
)
)
)
;; Top-level verification code to determine whether or not a Bitcoin transaction was mined in a prior Bitcoin block.
;; It takes the block header and block height, the transaction, and a merkle proof, and determines that:
;; * the block header corresponds to the block that was mined at the given Bitcoin height
;; * the transaction's merkle proof links it to the block header's merkle root.
;; The proof is a list of sibling merkle tree nodes that allow us to calculate the parent node from two children nodes in each merkle tree level,
;; the depth of the block's merkle tree, and the index in the block in which the given transaction can be found (starting from 0).
;; The first element in hashes must be the given transaction's sibling transaction's ID. This and the given transaction's txid are hashed to
;; calculate the parent hash in the merkle tree, which is then hashed with the *next* hash in the proof, and so on and so forth, until the final
;; hash can be compared against the block header's merkle root field. The tx-index tells us in which order to hash each pair of siblings.
;; Note that the proof hashes -- including the sibling txid -- must be _big-endian_ hashes, because this is how Bitcoin generates them.
;; This is the reverse of what you'd see in a block explorer!
;; Returns (ok true) if the proof checks out.
;; Returns (ok false) if not.
;; Returns (err ERR-PROOF-TOO-SHORT) if the proof doesn't contain enough intermediate hash nodes in the merkle tree.
(define-read-only (was-tx-mined? (block { header: (buff 80), height: uint }) (tx (buff 1024)) (proof { tx-index: uint, hashes: (list 12 (buff 32)), tree-depth: uint }))
(if (verify-block-header (get header block) (get height block))
(verify-merkle-proof (get-reversed-txid tx) (get merkle-root (try! (parse-block-header (get header block)))) proof)
(ok false)
)
)
| 0xedd750c5771559cb784481ccd014aea91fb0ce019dc54816b5ea51794549eec2 | 15,333 | success |
JoeToken | ;; use the SIP090 interface
(impl-trait 'ST000000000000000000002AMW42H.nft-trait.nft-trait)
;; define a new NFT. Make sure to replace NFT_NAME
(define-non-fungible-token <JoeToken> uint)
;; Store the last issues token ID
(define-data-var last-id uint u0)
;; Claim a new NFT
(define-public (claim)
(ok (mint tx-sender)))
;; SIP090: Transfer token to a specified principal
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and
(is-eq tx-sender sender))
;; Make sure to replace NFT_NAME
(match (nft-transfer? <JoeToken> token-id sender recipient)
success (ok success)
error (err {code: error}))
(err {code: error})))
;; SIP090: Get the owner of the specified token ID
(define-read-only (get-owner (token-id uint))
;; Make sure to replace NFT_NAME
(ok (nft-get-owner? <JoeToken> token-id)))
;; SIP090: Get the last token ID
(define-read-only (get-last-token-id)
(ok (var-get last-id)))
;; SIP090: Get the token URI. You can set it to any other URI
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://ipfs.io/ipfs/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6")))
(define-read-only (get-meta (token-id uint))
(if (is-eq token-id u1)
(ok (some {name: "JoeToken", uri: "https://ipfs.globalupload.io/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6", mime-type: "image/png"}))
(ok none)))
(define-read-only (get-nft-meta)
(ok (some {name: "JoeToken", uri: "https://ipfs.globalupload.io/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6", mime-type: "image/png"})))
;; Internal - Mint new NFT
(define-private (mint (new-owner principal))
(let ((next-id (+ u1 (var-get last-id))))
;; Make sure to replace NFT_NAME
(match (nft-mint? <JoeToken> next-id new-owner)
success
(begin
(var-set last-id next-id)
(ok success))
error (err {code: error})))) | 0x0e2f39798fc095761200a11f379e021cad85ff0c51e2b6a54a81496975424a99 | 15,554 | abort_by_response |
JoeToken-v3 | ;; use the SIP-009 interface
(impl-trait 'SP1JSH2FPE8BWNTP228YZ1AZZ0HE0064PS6RXRAY4.nft-trait.nft-trait)
;; define a new NFT.
(define-non-fungible-token JoeToken uint)
;; Store the last issues token ID
(define-data-var last-id uint u0)
;; Claim a new NFT
(define-public (claim)
(ok (mint tx-sender)))
;; SIP-009: Transfer token to a specified principal
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and
(is-eq tx-sender sender))
(match (nft-transfer? JoeToken token-id sender recipient)
success (ok success)
error (err {code: error}))
(err {code: error})))
;; SIP-009: Get the owner of the specified token ID
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? JoeToken token-id)))
;; SIP-009: Get the last token ID
(define-read-only (get-last-token-id)
(ok (var-get last-id)))
;; SIP-009: Get the token URI.
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://ipfs.io/ipfs/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6")))
(define-read-only (get-meta (token-id uint))
(if (is-eq token-id u1)
(ok (some {name: "JoeToken", uri: "https://ipfs.globalupload.io/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6", mime-type: "image/png"}))
(ok none)))
(define-read-only (get-nft-meta)
(ok (some {name: "JoeToken", uri: "https://ipfs.globalupload.io/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6", mime-type: "image/png"})))
;; Internal - Mint new NFT
(define-private (mint (new-owner principal))
(let ((next-id (+ u1 (var-get last-id))))
(match (nft-mint? JoeToken next-id new-owner)
success
(begin
(var-set last-id next-id)
(ok success))
error (err {code: error})))) | 0xf111c3a2038653c67df43b7a1ecfe312b761d91c90305c094257efe51072a31b | 15,648 | abort_by_response |
cc-ft-stx | ;; cc-ft-stx
;; wrap the native STX token into an SRC20 compatible token to be usable along other tokens
;; Use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard.ft-trait)
;; constants
;;
;; data maps and vars
;;
;; private functions
;;
;; public functions
;;
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(begin
(ok (print (stx-get-balance owner)))
)
)
(define-read-only (get-total-supply)
(ok stx-liquid-supply)
)
;; returns the token name
(define-read-only (get-name)
(ok "STX")
)
(define-read-only (get-symbol)
(ok "STX")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6)
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/stx.json"))
)
;; {
;; "name":"STX",
;; "description":"STX token, as a SIP-010 compatible token",
;; "image":"https://swapr.finance/tokens/stx.png",
;; "vector":"https://swapr.finance/tokens/stx.svg"
;; }
;; update: per https://github.com/stacksgov/sips/pull/25
;; (transfer ((amount uint) (from principal) (to principal) (memo (optional (buff 34)))) (response bool uint))
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (>= (stx-get-balance sender) amount)
(begin
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(stx-transfer? amount sender recipient))
(err u0))
)
| 0x7ccfc71f247949b318f33bb69a461e3d1da5edd2c87a5454b773ae1079c2f6f0 | 16,105 | success |
contract-21967684690 | ;; use the SIP-009 NFT interface
(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
;; define a new JoeToken NFT.
(define-non-fungible-token JoeToken uint)
;; Errors
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant nft-not-found-err (err u404)) ;; not found
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
;; Error Message Handling
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; Transfers tokens to a specified principal.
(define-public (transfer (from principal) (to principal) (token-id uint))
(begin
(asserts! (is-eq (some tx-sender) (nft-get-owner? JoeToken token-id)) nft-not-owned-err)
(asserts! (is-eq tx-sender from) nft-not-owned-err)
(asserts! (not (is-eq tx-sender to)) sender-equals-recipient-err)
(nft-transfer? JoeToken token-id tx-sender to)))
;; Gets the owner of the specified token ID.
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? JoeToken token-id)))
;; Gets the owner of the specified token ID.
(define-read-only (get-last-token-id)
(ok u1))
;; Defines external image as NFT metadata
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://ipfs.io/ipfs/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6")))
(define-read-only (get-meta (token-id uint))
(if (is-eq token-id u1)
(ok (some {name: "JoeToken", uri: "https://ipfs.globalupload.io/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6", mime-type: "image/png"}))
(ok none)))
(define-read-only (get-nft-meta)
(ok (some {name: "JoeToken", uri: "https://ipfs.globalupload.io/QmauCyd2NggdpiCR4MfwgbsGXPweKsRTB3kwVeHLYkjuW6", mime-type: "image/png"})))
;; Initialize the contract
(try! (nft-mint? JoeToken u1 tx-sender)) | 0x62ccb71e0386fb455a0199b7a2ace4c914315959dd6487e465f7d54b4853f7fb | 16,313 | abort_by_response |
MillieCoin | (define-non-fungible-token millie uint)
;; Public functions
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant nft-not-found-err (err u404)) ;; not found
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
;; Transfers tokens to a specified principal.
(define-public (transfer (from principal) (to principal) (token-id uint))
(begin
(asserts! (is-eq (some tx-sender) (nft-get-owner? millie token-id)) nft-not-owned-err)
(asserts! (is-eq tx-sender from) nft-not-owned-err)
(asserts! (not (is-eq tx-sender to)) sender-equals-recipient-err)
(nft-transfer? millie token-id tx-sender to)))
;; Gets the owner of the specified token ID.
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? millie token-id)))
;; Gets the owner of the specified token ID.
(define-read-only (get-last-token-id)
(ok u1))
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://ipfs.io/ipfs/QmW6E4DLT3RWfpBPEa9tgnpFJNnuYEmr7N8NJRgZmkkBCp")))
;; Initialize the contract
(try! (nft-mint? millie u1 tx-sender)) | 0x4cad48cbfa958e780e48512d9af060401dddc10295d4dcec67ddf15f4d5a1e7b | 16,327 | success |
sip-010-trait | (define-trait sip-010-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal (optional (buff 34))) (response bool uint))
;; the human readable name of the token
(name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(decimals () (response uint uint))
;; the balance of the passed principal
(balance-of (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
)
| 0x5e45ac84f74dd572c8de8d55caa1e5bb1f3a8607e7fc702436d804a76683bc5e | 16,442 | success |
sip-010 | (define-trait ft-trait
(
;; Transfer from the caller to a new principal with optional memo
(transfer (uint principal principal (optional (buff 34))) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance-of (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
) | 0x1508a980ed063e85a38728fe5caad0815e2f4ece0a1d77111185cc8c39b4b0ad | 16,628 | success |
wrapped-nothing-v7 | (define-constant ERR-UNAUTHORIZED u1)
(define-constant ERR-YOU-POOR u2)
(define-fungible-token wrapped-nthng)
(define-data-var token-uri (optional (string-utf8 256)) none)
(define-constant contract-creator tx-sender)
(impl-trait 'SP1X6M947Z7E58CNE0H8YJVJTVKS9VW0PHD4Q0A5F.sip-010.ft-trait)
(define-public (donate (amount uint))
(stx-transfer? amount tx-sender contract-creator))
(define-public (wrap-nthng (amount uint))
(if
(is-ok
(contract-call? .micro-nthng transfer (as-contract tx-sender) amount))
(begin
(ft-mint?
wrapped-nthng amount tx-sender)
)
(err ERR-YOU-POOR)))
(define-public (unwrap (amount uint))
(if
(is-ok (ft-burn? wrapped-nthng amount tx-sender))
(let ((unwrapper tx-sender))
(as-contract (contract-call? .micro-nthng transfer unwrapper amount)))
(err ERR-YOU-POOR)
))
;;;;;;;;;;;;;;;;;;;;; SIP 010 ;;;;;;;;;;;;;;;;;;;;;;
(define-public (transfer (amount uint) (from principal) (to principal) (memo (optional (buff 34))))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(ft-transfer? wrapped-nthng amount from to)
)
)
(define-read-only (get-name)
(ok "Wrapped Nothing v7"))
(define-read-only (get-symbol)
(ok "WMNO7"))
(define-read-only (get-decimals)
(ok u0))
(define-read-only (get-balance-of (user principal))
(ok (ft-get-balance wrapped-nthng user)))
(define-read-only (get-total-supply)
(ok (ft-get-supply wrapped-nthng)))
(define-public (set-token-uri (value (string-utf8 256)))
(if
(is-eq tx-sender contract-creator)
(ok (var-set token-uri (some value)))
(err ERR-UNAUTHORIZED)))
(define-read-only (get-token-uri)
(ok (var-get token-uri)))
;; send-many
(define-public (send-nothing (amount uint) (to principal))
(let ((transfer-ok (try! (transfer amount tx-sender to))))
(ok transfer-ok)))
(define-private (send-nothing-unwrap (recipient { to: principal, amount: uint }))
(send-nothing
(get amount recipient)
(get to recipient)))
(define-private (check-err (result (response bool uint))
(prior (response bool uint)))
(match prior ok-value result
err-value (err err-value)))
(define-public (send-many (recipients (list 200 { to: principal, amount: uint })))
(fold check-err
(map send-nothing-unwrap recipients)
(ok true))) | 0xcccefbdb941211702f0601e5ca2f91e72367771850e12149c64ce4b49fc34ab2 | 16,639 | success |
sip-010-trait-ft-standard | (define-trait sip-010-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal (optional (buff 34))) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
)
| 0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387 | 16,733 | success |
sip-010-trait-ft-standard | (define-trait sip-010-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal (optional (buff 34))) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
)
| 0x99e01721e57adc2c24f7d371b9d302d581dba1d27250c7e25ea5f241af14c387 | 16,733 | success |
hiro-hackathon-winner-2021 | ;; use the SIP009 interface
(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
;; define a new NFT
(define-non-fungible-token hiro-hackathon-winner-2021 uint)
;; list of NFT winners
(define-constant initial-members (list
'SP1X6M947Z7E58CNE0H8YJVJTVKS9VW0PHD4Q0A5F
'SPGCWKN03B99HBCMJT9ZE035RQJ419P7H3WC70AJ
'SPTYAX4NG2BPNDJMS35QZ0YKFS3MGDFM4JC04ZKB
'SP221YEHD09G4KZCEB8D57DB1J33HZFT5S4SHMKAN))
;; SIP009: Transfer token to a specified principal
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and (is-owner token-id sender) (or (is-eq sender tx-sender ) (is-eq sender contract-caller)))
(match (nft-transfer? hiro-hackathon-winner-2021 token-id sender recipient)
success (ok success)
error (err u500))
(err u401)))
;; SIP009: Get the owner of the specified token ID
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? hiro-hackathon-winner-2021 token-id)))
;; SIP009: Get the last token ID
(define-read-only (get-last-token-id)
(ok (len initial-members)))
;; SIP009: Get the token URI. You can set it to any other URI
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://www.hiro.so/blog/hiro-internal-hackathon-recap")))
;; NFT Metadata
(define-read-only (get-nft-meta)
(ok {name: "First Ever Hiro Hackathon Winner", uri: "https://ipfs.io/ipfs/QmXTeyFsiCGsB6st5FTbvc78RkXG8hKo5SxtCN8cv8ity3/hiro-first-hackathon.webm", mime-type: "video/webm",
hash: "e4ce55dd89113b846c4d43f7018f66e57e7b12d6af960e2a143f91457d27e1f0"}))
;; Internal - distribute NFTs
(map mint initial-members)
;; Internal - Mint an NFT
(define-private (mint (owner principal))
(match (nft-mint? hiro-hackathon-winner-2021 (unwrap! (index-of initial-members owner) (err {code: u404})) owner)
success
(ok success)
error (err {code: error})))
;; Internal - is the user an owner
(define-private (is-owner (token-id uint) (user principal))
(is-eq user
;; if no owner, return false
(unwrap! (nft-get-owner? hiro-hackathon-winner-2021 token-id) false))) | 0x0fca15db3109a4cbd6d2b7ed1668e30021635250b68f78a2bacf225afa5c9935 | 17,140 | abort_by_response |
drunk-silver-scorpion | ;; hello-world contract
(define-constant sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR)
(define-constant recipient 'SP2XRA36RN7QTZSZX6YRPXKYSVHP7CMQ0FMHME0TF)
(define-fungible-token novel-token-19)
(begin (ft-mint? novel-token-19 u12 sender))
(begin (ft-transfer? novel-token-19 u2 sender recipient))
(define-non-fungible-token hello-nft uint)
(begin (nft-mint? hello-nft u1 sender))
(begin (nft-mint? hello-nft u2 sender))
(begin (nft-transfer? hello-nft u1 sender recipient))
(define-public (test-emit-event)
(begin
(print "Event! Hello world")
(ok u1)))
(begin (test-emit-event))
(define-public (test-event-types)
(begin
(unwrap-panic (ft-mint? novel-token-19 u3 recipient))
(unwrap-panic (nft-mint? hello-nft u2 recipient))
(unwrap-panic (stx-transfer? u60 tx-sender 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR))
(unwrap-panic (stx-burn? u20 tx-sender))
(ok u1)))
(define-map store {key: (buff 32)} {value: (buff 32)})
(define-public (get-value (key (buff 32)))
(begin
(match (map-get? store {key: key})
entry (ok (get value entry))
(err 0))))
(define-public (set-value (key (buff 32)) (value (buff 32)))
(begin
(map-set store {key: key} {value: value})
(ok u1))) | 0x75cb5fc04fa901497cec25a8890770dbf7fca411b9bde5c6864028312128bcfd | 17,428 | success |
wrapped-nothing-7 | (define-constant ERR-UNAUTHORIZED u1)
(define-constant ERR-YOU-POOR u2)
(define-fungible-token wrapped-nthng)
(define-data-var token-uri (optional(string-utf8 256)) none)
(define-constant contract-creator tx-sender)
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait)
(define-public (donate (amount uint))
(stx-transfer? amount tx-sender contract-creator))
(define-public (wrap-nthng (amount uint))
(if
(is-ok
(contract-call? SP32AEEF6WW5Y0NMJ1S8SBSZDAY8R5J32NBZFPKKZ.micro-nthng transfer (as-contract tx-sender) amount))
(begin
(ft-mint?
wrapped-nthng amount tx-sender)
)
(err ERR-YOU-POOR)))
(define-public (unwrap (amount uint))
(if
(is-ok (ft-burn? wrapped-nthng amount tx-sender))
(let ((unwrapper tx-sender))
(as-contract (contract-call? SP32AEEF6WW5Y0NMJ1S8SBSZDAY8R5J32NBZFPKKZ.micro-nthng transfer unwrapper amount)))
(err ERR-YOU-POOR)
))
;; SIP-010 ;;
(define-public (transfer (amount uint) (from principal) (to principal) (memo (optional (buff 34))))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(ft-transfer? wrapped-nthng amount from to)
)
)
(define-read-only (get-name)
(ok "Wrapped Nothing 7"))
(define-read-only (get-symbol)
(ok "WMNO"))
(define-read-only (get-decimals)
(ok u0))
(define-read-only (get-balance (user principal))
(ok (ft-get-balance wrapped-nthng user)))
(define-read-only (get-total-supply)
(ok (ft-get-supply wrapped-nthng)))
(define-public (set-token-uri (value (string-utf8 256)))
(if
(is-eq tx-sender contract-creator)
(ok (var-set token-uri (some value)))
(err ERR-UNAUTHORIZED)))
(define-read-only (get-token-uri)
(ok (var-get token-uri)))
;; send-many
(define-public (send-nothing (amount uint) (to principal))
(let ((transfer-ok (try! (transfer amount tx-sender to))))
(ok transfer-ok)))
(define-private (send-nothing-unwrap (recipient { to: principal, amount: uint }))
(send-nothing
(get amount recipient)
(get to recipient)))
(define-private (check-err (result (response bool uint))
(prior (response bool uint)))
(match prior ok-value result
err-value (err err-value)))
(define-public (send-many (recipients (list 200 { to: principal, amount: uint })))
(fold check-err
(map send-nothing-unwrap recipients)
(ok true))) | 0x2890147c1f38c1a389a342641a4d83f2fc75c34e0f926c0e215c63e9a1ad0a50 | 17,617 | abort_by_response |
wrapped-nothing-v8 | (define-constant ERR-UNAUTHORIZED u1)
(define-constant ERR-YOU-POOR u2)
(define-fungible-token wrapped-nthng)
(define-data-var token-uri (optional (string-utf8 256)) none)
(define-constant contract-creator tx-sender)
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait)
(define-public (donate (amount uint))
(stx-transfer? amount tx-sender contract-creator))
(define-public (wrap-nthng (amount uint))
(if
(is-ok
(contract-call? .micro-nthng transfer (as-contract tx-sender) amount))
(begin
(ft-mint?
wrapped-nthng amount tx-sender)
)
(err ERR-YOU-POOR)))
(define-public (unwrap (amount uint))
(if
(is-ok (ft-burn? wrapped-nthng amount tx-sender))
(let ((unwrapper tx-sender))
(as-contract (contract-call? .micro-nthng transfer unwrapper amount)))
(err ERR-YOU-POOR)
))
;;;;;;;;;;;;;;;;;;;;; SIP 010 ;;;;;;;;;;;;;;;;;;;;;;
(define-public (transfer (amount uint) (from principal) (to principal) (memo (optional (buff 34))))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(ft-transfer? wrapped-nthng amount from to)
)
)
(define-read-only (get-name)
(ok "Wrapped Nothing v8"))
(define-read-only (get-symbol)
(ok "WMNO8"))
(define-read-only (get-decimals)
(ok u0))
(define-read-only (get-balance (user principal))
(ok (ft-get-balance wrapped-nthng user)))
(define-read-only (get-total-supply)
(ok (ft-get-supply wrapped-nthng)))
(define-public (set-token-uri (value (string-utf8 256)))
(if
(is-eq tx-sender contract-creator)
(ok (var-set token-uri (some value)))
(err ERR-UNAUTHORIZED)))
(define-read-only (get-token-uri)
(ok (var-get token-uri)))
;; send-many
(define-public (send-nothing (amount uint) (to principal))
(let ((transfer-ok (try! (transfer amount tx-sender to))))
(ok transfer-ok)))
(define-private (send-nothing-unwrap (recipient { to: principal, amount: uint }))
(send-nothing
(get amount recipient)
(get to recipient)))
(define-private (check-err (result (response bool uint))
(prior (response bool uint)))
(match prior ok-value result
err-value (err err-value)))
(define-public (send-many (recipients (list 200 { to: principal, amount: uint })))
(fold check-err
(map send-nothing-unwrap recipients)
(ok true))) | 0x8200e6ada189dd76dc17e0ad8e3857348bb7e3cda7c2600877f59d60eaafda64 | 17,715 | success |
stx-history | ;; historical stacks balance of user
(define-read-only (get-balance (user principal) (bh uint))
(ok (at-block (unwrap! (get-block-info? id-header-hash bh) (err u9999)) (stx-get-balance user)))
)
| 0x92b0bc71f463aac245faebc3b5f47723fb63c768fe07854f042fccadde93cbab | 18,035 | success |
cc-ft-cxc | ;; cc-ft-cxc
;; CrossCheck Token
;; we implement the sip-010
;; In Mainnet Use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
(define-fungible-token cxc u19000000000000)
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard)
;; public functions
;;
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance cxc owner))
)
;; returns the total number of tokens
(define-read-only (get-total-supply)
(ok (ft-get-supply cxc))
)
;; returns the token name
(define-read-only (get-name)
(ok "CrossCheck")
)
(define-read-only (get-symbol)
(ok "CXC")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6) ;; because we can, and interesting for testing wallets and other clients
)
(define-read-only (get-token-uri)
(ok (some u"https://paradigma.global/tokens/crosscheck.json"))
)
;; {
;; "name":"CrossCheck",
;; "description":"CrossCheck token, used as a token",
;; "image":"https://paradigma.global/tokens/crosscheck.png",
;; "vector":"https://paradigma.global/tokens/crosscheck.svg"
;; }
;; (transfer (uint principal principal) (response bool uint))
;; amount sender recipient
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (>= (ft-get-balance cxc sender) amount)
(begin
(print "crosscheck.transfer")
(print amount)
(print tx-sender)
(print recipient)
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(print (ft-transfer? cxc amount sender recipient))
)
(err u0)
)
)
| 0x25dd440acbe0fe9ad518d149614fd3527feb06153039421463df6014204fab66 | 18,097 | abort_by_response |
greet | ;; hello-world contract
(define-public (greet)
(begin
(print "Hello world!")
(ok u0)))
| 0x9c36b02ccb66fcf39cbfb49af573f82a55588afd1bd62068448f8bf7b4c7f6ff | 18,153 | success |
xverse-pool-v2 | ;; (impl-trait ST33GW755MQQP6FZ58S423JJ23GBKK5ZKH3MGR55N.pool-registry-v2.pox-trait-ext)
;; (impl-trait SP1K1A1PMGW2ZJCNF46NWZWHG8TS1D23EGH1KNK60.pool-registry-v1.pox-trait-ext)
(define-constant err-missing-user-pox-addr (err u100))
(define-constant err-map-set-failed (err u101))
(define-constant err-pox-failed (err u102))
(define-constant err-delegate-below-minimum (err u103))
(define-constant err-missing-user (err u104))
(define-constant err-non-positive-amount (err u105))
(define-constant err-not-pool-member (err u106))
(define-constant err-no-user-info (err u107))
(define-constant err-no-stacker-info (err u108))
;; keep track of the last delegation
;; pox-addr: raw bytes of user's account to receive rewards, can be encoded as btc or stx address
;; cycle: cycle id of time of delegation
;; lock-period: desired number of cycles to lock
(define-map user-data principal {pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint})
;; Keep track of stackers grouped by pool, reward-cycle id and lock-period
;; "grouped-stackers-len" returns the number of lists for the given group
;; "grouped-stackers" returns the actual list
(define-map grouped-stackers {pool: principal, reward-cycle: uint, lock-period: uint, index: uint}
(list 30 {lock-amount: uint, stacker: principal, unlock-burn-height: uint, pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint}))
(define-map grouped-stackers-len {pool: principal, reward-cycle: uint, lock-period: uint} uint)
;; Keep track of total stxs stacked grouped by pool, reward-cycle id and lock-period
(define-map grouped-totals {pool: principal, reward-cycle: uint, lock-period: uint} uint)
;;
;; Genesis pox function calls
;;
;; Backport of .pox's burn-height-to-reward-cycle
(define-private (burn-height-to-reward-cycle (height uint))
(let (
(pox-info (unwrap-panic (contract-call? 'SP000000000000000000002Q6VF78.pox get-pox-info)))
)
(/ (- height (get first-burnchain-block-height pox-info)) (get reward-cycle-length pox-info)))
)
;; Backport of .pox's reward-cycle-to-burn-height
(define-private (reward-cycle-to-burn-height (cycle uint))
(let (
(pox-info (unwrap-panic (contract-call? 'SP000000000000000000002Q6VF78.pox get-pox-info)))
)
(+ (get first-burnchain-block-height pox-info) (* cycle (get reward-cycle-length pox-info))))
)
;; What's the current PoX reward cycle?
(define-private (current-pox-reward-cycle)
(burn-height-to-reward-cycle burn-block-height))
;; Get stacker info
(define-private (pox-get-stacker-info (user principal))
(contract-call? 'SP000000000000000000002Q6VF78.pox get-stacker-info user))
;; Revoke and delegate stx
(define-private (pox-delegate-stx (amount-ustx uint) (delegate-to principal) (until-burn-ht (optional uint)))
(let ((result-revoke (contract-call? 'SP000000000000000000002Q6VF78.pox revoke-delegate-stx)))
(match (contract-call? 'SP000000000000000000002Q6VF78.pox delegate-stx amount-ustx delegate-to until-burn-ht none)
success (ok success)
error (err (* u1000 (to-uint error))))))
;;
;; Helper functions
;;
(define-private (min (amount-1 uint) (amount-2 uint))
(if (< amount-1 amount-2)
amount-1
amount-2))
(define-private (asserts-panic (value bool))
(unwrap-panic (if value (some true) none)))
;;
;; Helper functions for "grouped-stackers" map
;;
(define-private (merge-details (stacker {lock-amount: uint, stacker: principal, unlock-burn-height: uint}) (user {pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint}))
{lock-amount: (get lock-amount stacker),
stacker: (get stacker stacker),
unlock-burn-height: (get unlock-burn-height stacker),
pox-addr: (get pox-addr user),
cycle: (get cycle user),
lock-period: (get lock-period user)})
(define-private (insert-in-new-list (pool principal) (reward-cycle uint) (last-index uint) (details {lock-amount: uint, stacker: principal, unlock-burn-height: uint, pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint}))
(let ((index (+ last-index u1)))
(asserts-panic (map-insert grouped-stackers (print {pool: pool, reward-cycle: reward-cycle, lock-period: (get lock-period details), index: index}) (list details)))
(asserts-panic (map-set grouped-stackers-len {pool: pool, reward-cycle: reward-cycle, lock-period: (get lock-period details)} index))))
(define-private (map-set-details (pool principal) (details {lock-amount: uint, stacker: principal, unlock-burn-height: uint, pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint}))
(let ((reward-cycle (+ (burn-height-to-reward-cycle burn-block-height) u1))
(lock-period (get lock-period details)))
(let ((last-index (get-status-list-length pool reward-cycle lock-period)))
(match (map-get? grouped-stackers {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period, index: last-index})
stackers (match (as-max-len? (append stackers details) u30)
new-list (map-set grouped-stackers (print {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period, index: last-index}) new-list)
(insert-in-new-list pool reward-cycle last-index details))
(map-insert grouped-stackers (print {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period, index: last-index}) (list details)))
(map-set grouped-totals {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period} (+ (get-total pool reward-cycle lock-period) (get lock-amount details))))))
;; Genesis delegate-stack-stx call.
;; Stores the result in "grouped-stackers".
(define-private (pox-delegate-stack-stx (details {user: principal, amount-ustx: uint})
(context (tuple
(pox-address (tuple (hashbytes (buff 20)) (version (buff 1))))
(start-burn-ht uint)
(lock-period uint)
(result (list 30 (response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) uint))))))
(let ((user (get user details)))
(let ((pox-address (get pox-address context))
(start-burn-ht (get start-burn-ht context))
(lock-period (get lock-period context))
(amount-ustx (min (get amount-ustx details) (stx-get-balance user))))
(let ((stack-result
(if (> amount-ustx u0)
(match (map-get? user-data user)
user-details
(match (contract-call? 'SP000000000000000000002Q6VF78.pox delegate-stack-stx
user amount-ustx
pox-address start-burn-ht lock-period)
stacker-details (begin
(map-set-details tx-sender (merge-details stacker-details user-details))
(ok stacker-details))
error (err (* u1000 (to-uint error))))
err-missing-user)
err-non-positive-amount)))
{pox-address: pox-address,
start-burn-ht: start-burn-ht,
lock-period: lock-period,
result: (unwrap-panic (as-max-len? (append (get result context) stack-result) u30))}))))
;;
;; Public function
;;
;; As defined by "pool-registry.pox-trait-ext" trait.
;; Users call this function to delegate the stacking rights to a pool.
;;
;; user-pox-addr: raw bytes of user's address that should be used for payout of rewards by pool admins.
;; lock-period: desired lock period that pool admin should respect.
(define-public (delegate-stx (amount-ustx uint) (delegate-to principal) (until-burn-ht (optional uint))
(pool-pox-addr (optional (tuple (hashbytes (buff 20)) (version (buff 1)))))
(user-pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))
(lock-period uint))
(begin
(asserts! (map-set user-data tx-sender
{pox-addr: user-pox-addr, cycle: (current-pox-reward-cycle), lock-period: lock-period})
err-map-set-failed)
(pox-delegate-stx amount-ustx delegate-to until-burn-ht)))
;; Pool admins call this function to lock stacks of their pool members in batches
(define-public (delegate-stack-stx (users (list 30 (tuple
(user principal)
(amount-ustx uint))))
(pox-address { version: (buff 1), hashbytes: (buff 20) })
(start-burn-ht uint)
(lock-period uint))
(let ((stack-result (get result (fold pox-delegate-stack-stx users {start-burn-ht: start-burn-ht, pox-address: pox-address, lock-period: lock-period, result: (list)}))))
(ok stack-result)))
;;
;; Read-only functions
;;
;; Returns the user's stacking details from pox contract,
;; the user's delegation details from "user-data" and the
;; total locked stacks for the given pool and user's stacking parameters.
;; Note, that user can stack with a different pool, results need to verify stacker-info.pox-addr
(define-read-only (get-status (pool principal) (user principal))
(match (pox-get-stacker-info user)
stacker-info (match (map-get? user-data user)
user-info
(ok {stacker-info: stacker-info, user-info: user-info, total: (get-total pool (get first-reward-cycle stacker-info) (get lock-period stacker-info))})
err-no-user-info)
err-no-stacker-info))
;; Get hte number of lists of stackers that have locked their stx for the given pool, cycle and lock-period.
(define-read-only (get-status-list-length (pool principal) (reward-cycle uint) (lock-period uint))
(default-to u0 (map-get? grouped-stackers-len {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period}))
)
;; Get a list of stackers that have locked their stx for the given pool, cycle and lock-period.
;; index: must be smaller than get-status-list-length
(define-read-only (get-status-list (pool principal) (reward-cycle uint) (lock-period uint) (index uint))
{total: (get-total pool reward-cycle lock-period),
status-list: (map-get? grouped-stackers {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period, index: index})}
)
;; Get total stacks locked by given pool, reward-cycle and lock-period.
;; The total for a given reward cycle needs to be calculated off-chain
;; depending on the pool's policy.
(define-read-only (get-total (pool principal) (reward-cycle uint) (lock-period uint))
(default-to u0 (map-get? grouped-totals {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period}))
)
| 0xbdf1823f1034d3c11a3ca97eea2e063d4fae96e2b03ca07647a915006fd9322c | 18,202 | success |
hiro-hackathon-winner-2021 | ;; use the SIP009 interface
(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
;; define a new NFT
(define-non-fungible-token hiro-hackathon-winner-2021 uint)
;; list of NFT winners
(define-constant initial-members (list
'SP1X6M947Z7E58CNE0H8YJVJTVKS9VW0PHD4Q0A5F
'SPGCWKN03B99HBCMJT9ZE035RQJ419P7H3WC70AJ
'SPTYAX4NG2BPNDJMS35QZ0YKFS3MGDFM4JC04ZKB))
;; SIP009: Transfer token to a specified principal
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and (is-owner token-id sender) (or (is-eq sender tx-sender ) (is-eq sender contract-caller)))
(match (nft-transfer? hiro-hackathon-winner-2021 token-id sender recipient)
success (ok success)
error (err u500))
(err u401)))
;; SIP009: Get the owner of the specified token ID
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? hiro-hackathon-winner-2021 token-id)))
;; SIP009: Get the last token ID
(define-read-only (get-last-token-id)
(ok (len initial-members)))
;; SIP009: Get the token URI. You can set it to any other URI
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://www.hiro.so/blog/hiro-internal-hackathon-recap")))
;; NFT Metadata
(define-read-only (get-nft-meta)
(ok {name: "First Ever Hiro Hackathon Winner", uri: "https://ipfs.io/ipfs/QmXTeyFsiCGsB6st5FTbvc78RkXG8hKo5SxtCN8cv8ity3/hiro-first-hackathon.webm", mime-type: "video/webm",
hash: "e4ce55dd89113b846c4d43f7018f66e57e7b12d6af960e2a143f91457d27e1f0"}))
;; Internal - distribute NFTs
(map mint initial-members)
;; Internal - Mint an NFT
(define-private (mint (owner principal))
(match (nft-mint? hiro-hackathon-winner-2021 (unwrap! (index-of initial-members owner) (err {code: u404})) owner)
success
(ok success)
error (err {code: error})))
;; Internal - is the user an owner
(define-private (is-owner (token-id uint) (user principal))
(is-eq user
;; if no owner, return false
(unwrap! (nft-get-owner? hiro-hackathon-winner-2021 token-id) false))) | 0x5d1704291538dbeb201161f9f052f79281bea2a944f8c22e4ebdf67005d2b429 | 18,296 | success |
xverse-pool-v2 | ;; (impl-trait ST33GW755MQQP6FZ58S423JJ23GBKK5ZKH3MGR55N.pool-registry-v2.pox-trait-ext)
;; (impl-trait SP1K1A1PMGW2ZJCNF46NWZWHG8TS1D23EGH1KNK60.pool-registry-v1.pox-trait-ext)
(define-constant err-missing-user-pox-addr (err u100))
(define-constant err-map-set-failed (err u101))
(define-constant err-pox-failed (err u102))
(define-constant err-delegate-below-minimum (err u103))
(define-constant err-missing-user (err u104))
(define-constant err-non-positive-amount (err u105))
(define-constant err-not-pool-member (err u106))
(define-constant err-no-user-info (err u107))
(define-constant err-no-stacker-info (err u108))
;; keep track of the last delegation
;; pox-addr: raw bytes of user's account to receive rewards, can be encoded as btc or stx address
;; cycle: cycle id of time of delegation
;; lock-period: desired number of cycles to lock
(define-map user-data principal {pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint})
;; Keep track of stackers grouped by pool, reward-cycle id and lock-period
;; "grouped-stackers-len" returns the number of lists for the given group
;; "grouped-stackers" returns the actual list
(define-map grouped-stackers {pool: principal, reward-cycle: uint, lock-period: uint, index: uint}
(list 30 {lock-amount: uint, stacker: principal, unlock-burn-height: uint, pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint}))
(define-map grouped-stackers-len {pool: principal, reward-cycle: uint, lock-period: uint} uint)
;; Keep track of total stxs stacked grouped by pool, reward-cycle id and lock-period
(define-map grouped-totals {pool: principal, reward-cycle: uint, lock-period: uint} uint)
;;
;; Genesis pox function calls
;;
;; Backport of .pox's burn-height-to-reward-cycle
(define-private (burn-height-to-reward-cycle (height uint))
(let (
(pox-info (unwrap-panic (contract-call? 'SP000000000000000000002Q6VF78.pox get-pox-info)))
)
(/ (- height (get first-burnchain-block-height pox-info)) (get reward-cycle-length pox-info)))
)
;; Backport of .pox's reward-cycle-to-burn-height
(define-private (reward-cycle-to-burn-height (cycle uint))
(let (
(pox-info (unwrap-panic (contract-call? 'SP000000000000000000002Q6VF78.pox get-pox-info)))
)
(+ (get first-burnchain-block-height pox-info) (* cycle (get reward-cycle-length pox-info))))
)
;; What's the current PoX reward cycle?
(define-private (current-pox-reward-cycle)
(burn-height-to-reward-cycle burn-block-height))
;; Get stacker info
(define-private (pox-get-stacker-info (user principal))
(contract-call? 'SP000000000000000000002Q6VF78.pox get-stacker-info user))
;; Revoke and delegate stx
(define-private (pox-delegate-stx (amount-ustx uint) (delegate-to principal) (until-burn-ht (optional uint)))
(let ((result-revoke (contract-call? 'SP000000000000000000002Q6VF78.pox revoke-delegate-stx)))
(match (contract-call? 'SP000000000000000000002Q6VF78.pox delegate-stx amount-ustx delegate-to until-burn-ht none)
success (ok success)
error (err (* u1000 (to-uint error))))))
;;
;; Helper functions
;;
(define-private (min (amount-1 uint) (amount-2 uint))
(if (< amount-1 amount-2)
amount-1
amount-2))
(define-private (asserts-panic (value bool))
(unwrap-panic (if value (some true) none)))
;;
;; Helper functions for "grouped-stackers" map
;;
(define-private (merge-details (stacker {lock-amount: uint, stacker: principal, unlock-burn-height: uint}) (user {pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint}))
{lock-amount: (get lock-amount stacker),
stacker: (get stacker stacker),
unlock-burn-height: (get unlock-burn-height stacker),
pox-addr: (get pox-addr user),
cycle: (get cycle user),
lock-period: (get lock-period user)})
(define-private (insert-in-new-list (pool principal) (reward-cycle uint) (last-index uint) (details {lock-amount: uint, stacker: principal, unlock-burn-height: uint, pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint}))
(let ((index (+ last-index u1)))
(asserts-panic (map-insert grouped-stackers (print {pool: pool, reward-cycle: reward-cycle, lock-period: (get lock-period details), index: index}) (list details)))
(asserts-panic (map-set grouped-stackers-len {pool: pool, reward-cycle: reward-cycle, lock-period: (get lock-period details)} index))))
(define-private (map-set-details (pool principal) (details {lock-amount: uint, stacker: principal, unlock-burn-height: uint, pox-addr: (tuple (hashbytes (buff 20)) (version (buff 1))), cycle: uint, lock-period: uint}))
(let ((reward-cycle (+ (burn-height-to-reward-cycle burn-block-height) u1))
(lock-period (get lock-period details)))
(let ((last-index (get-status-list-length pool reward-cycle lock-period)))
(match (map-get? grouped-stackers {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period, index: last-index})
stackers (match (as-max-len? (append stackers details) u30)
new-list (map-set grouped-stackers (print {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period, index: last-index}) new-list)
(insert-in-new-list pool reward-cycle last-index details))
(map-insert grouped-stackers (print {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period, index: last-index}) (list details)))
(map-set grouped-totals {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period} (+ (get-total pool reward-cycle lock-period) (get lock-amount details))))))
;; Genesis delegate-stack-stx call.
;; Stores the result in "grouped-stackers".
(define-private (pox-delegate-stack-stx (details {user: principal, amount-ustx: uint})
(context (tuple
(pox-address (tuple (hashbytes (buff 20)) (version (buff 1))))
(start-burn-ht uint)
(lock-period uint)
(result (list 30 (response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) uint))))))
(let ((user (get user details)))
(let ((pox-address (get pox-address context))
(start-burn-ht (get start-burn-ht context))
(lock-period (get lock-period context))
(amount-ustx (min (get amount-ustx details) (stx-get-balance user))))
(let ((stack-result
(if (> amount-ustx u0)
(match (map-get? user-data user)
user-details
(match (contract-call? 'SP000000000000000000002Q6VF78.pox delegate-stack-stx
user amount-ustx
pox-address start-burn-ht lock-period)
stacker-details (begin
(map-set-details tx-sender (merge-details stacker-details user-details))
(ok stacker-details))
error (err (* u1000 (to-uint error))))
err-missing-user)
err-non-positive-amount)))
{pox-address: pox-address,
start-burn-ht: start-burn-ht,
lock-period: lock-period,
result: (unwrap-panic (as-max-len? (append (get result context) stack-result) u30))}))))
;;
;; Public function
;;
;; As defined by "pool-registry.pox-trait-ext" trait.
;; Users call this function to delegate the stacking rights to a pool.
;;
;; user-pox-addr: raw bytes of user's address that should be used for payout of rewards by pool admins.
;; lock-period: desired lock period that pool admin should respect.
(define-public (delegate-stx (amount-ustx uint) (delegate-to principal) (until-burn-ht (optional uint))
(pool-pox-addr (optional (tuple (hashbytes (buff 20)) (version (buff 1)))))
(user-pox-addr (tuple (hashbytes (buff 20)) (version (buff 1))))
(lock-period uint))
(begin
(asserts! (map-set user-data tx-sender
{pox-addr: user-pox-addr, cycle: (current-pox-reward-cycle), lock-period: lock-period})
err-map-set-failed)
(pox-delegate-stx amount-ustx delegate-to until-burn-ht)))
;; Pool admins call this function to lock stacks of their pool members in batches
(define-public (delegate-stack-stx (users (list 30 (tuple
(user principal)
(amount-ustx uint))))
(pox-address { version: (buff 1), hashbytes: (buff 20) })
(start-burn-ht uint)
(lock-period uint))
(let ((stack-result (get result (fold pox-delegate-stack-stx users {start-burn-ht: start-burn-ht, pox-address: pox-address, lock-period: lock-period, result: (list)}))))
(ok stack-result)))
;;
;; Read-only functions
;;
;; Returns the user's stacking details from pox contract,
;; the user's delegation details from "user-data" and the
;; total locked stacks for the given pool and user's stacking parameters.
;; Note, that user can stack with a different pool, results need to verify stacker-info.pox-addr
(define-read-only (get-status (pool principal) (user principal))
(match (pox-get-stacker-info user)
stacker-info (match (map-get? user-data user)
user-info
(ok {stacker-info: stacker-info, user-info: user-info, total: (get-total pool (get first-reward-cycle stacker-info) (get lock-period stacker-info))})
err-no-user-info)
err-no-stacker-info))
;; Get hte number of lists of stackers that have locked their stx for the given pool, cycle and lock-period.
(define-read-only (get-status-list-length (pool principal) (reward-cycle uint) (lock-period uint))
(default-to u0 (map-get? grouped-stackers-len {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period}))
)
;; Get a list of stackers that have locked their stx for the given pool, cycle and lock-period.
;; index: must be smaller than get-status-list-length
(define-read-only (get-status-list (pool principal) (reward-cycle uint) (lock-period uint) (index uint))
{total: (get-total pool reward-cycle lock-period),
status-list: (map-get? grouped-stackers {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period, index: index})}
)
;; Get total stacks locked by given pool, reward-cycle and lock-period.
;; The total for a given reward cycle needs to be calculated off-chain
;; depending on the pool's policy.
(define-read-only (get-total (pool principal) (reward-cycle uint) (lock-period uint))
(default-to u0 (map-get? grouped-totals {pool: pool, reward-cycle: reward-cycle, lock-period: lock-period}))
)
| 0x57afe1ea0dcb9249f48bdaa2e70f280ea539cbbc6fbc19e4119201ef1a97cf05 | 18,649 | success |
bizarre-peach-earwig | ;; shorten
;; link shortener built on stacks
(define-constant owner 'ST3AA33M8SS15A30ETXE134ZXD8TNEDHT8Q955G40)
(define-constant ERR_PANIC 0)
(define-constant ERR_LINK_DOES_NOT_EXIST 1)
(define-constant ERR_LINK_ALREADY_EXISTS 2)
(define-constant ERR_COULD_NOT_FUND 3)
(define-map links
(string-ascii 5)
{ url: (string-ascii 1000), owner: principal })
(define-public (create-link (code (string-ascii 5)) (url (string-ascii 1000)))
(begin
(unwrap!
(stx-transfer? u100 tx-sender owner)
(err ERR_COULD_NOT_FUND))
(map-insert links code {
url: url,
owner: tx-sender
})
(ok true)))
(define-read-only (get-link (code (string-ascii 5)))
(match (map-get? links code)
link
(ok link)
(err ERR_LINK_DOES_NOT_EXIST)))
| 0x1bd0330faa194ba327d633513f8b0e604dfc0485b9c90930926aff8cba7d7eb9 | 19,020 | success |
dmt-mine | ;; error codes
(define-constant ERR-NO-WINNER u0)
(define-constant ERR-NO-SUCH-MINER u1)
(define-constant ERR-IMMATURE-TOKEN-REWARD u2)
(define-constant ERR-UNAUTHORIZED u3)
(define-constant ERR-ALREADY-CLAIMED u4)
(define-constant ERR-STACKING-NOT-AVAILABLE u5)
(define-constant ERR-CANNOT-STACK u6)
(define-constant ERR-INSUFFICIENT-BALANCE u7)
(define-constant ERR-ALREADY-MINED u8)
(define-constant ERR-ROUND-FULL u9) ;; deprecated - this error is not used anymore
(define-constant ERR-NOTHING-TO-REDEEM u10)
(define-constant ERR-CANNOT-MINE u11)
(define-constant ERR-MINER-ALREADY-REGISTERED u12)
(define-constant ERR-MINING-ACTIVATION-THRESHOLD-REACHED u13)
(define-constant ERR-MINER-ID-NOT-FOUND u14)
(define-constant ERR-TOO-SMALL-COMMITMENT u15)
;; Tailor to your needs.
(define-constant TOKEN-REWARD-MATURITY u5) ;; how long a miner must wait before claiming their minted tokens
(define-constant FIRST-STACKING-BLOCK u340282366920938463463374607431768211455) ;; Stacks block height when Stacking is available
(define-constant REWARD-CYCLE-LENGTH u2100) ;; how long a reward cycle is
(define-constant MAX-REWARD-CYCLES u32) ;; how many reward cycles a Stacker can Stack their tokens for
(define-constant MAX-MINERS-COUNT u128) ;; maximum amount of miners in one block
(define-constant LONG-UINT-LIST (list
u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15 u16
u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31 u32
u33 u34 u35 u36 u37 u38 u39 u40 u41 u42 u43 u44 u45 u46 u47 u48
u49 u50 u51 u52 u53 u54 u55 u56 u57 u58 u59 u60 u61 u62 u63 u64
u65 u66 u67 u68 u69 u70 u71 u72 u73 u74 u75 u76 u77 u78 u79 u80
u81 u82 u83 u84 u85 u86 u87 u88 u89 u90 u91 u92 u93 u94 u95 u96
u97 u98 u99 u100 u101 u102 u103 u104 u105 u106 u107 u108 u109 u110 u111 u112
u113 u114 u115 u116 u117 u118 u119 u120 u121 u122 u123 u124 u125 u126 u127 u128
))
;; Define city wallet and mining split
(define-constant CITY_CUSTODIED_WALLET 'ST31270FK25JBGCRWYT7RNK90E946R8VW6SZYSQR6) ;; the custodied wallet address for the city
(define-data-var city-wallet principal CITY_CUSTODIED_WALLET) ;; variable used in place of constant for easier testing
(define-constant SPLIT_STACKER_PERCENTAGE u70) ;; 70% split to stackers of the CityCoin
(define-constant SPLIT_CITY_PERCENTAGE u30) ;; 30% split to custodied wallet address for the city
;; NOTE: must be as long as MAX-REWARD-CYCLES
(define-constant REWARD-CYCLE-INDEXES (list u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15 u16 u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31))
;; lookup table for converting 1-byte buffers to uints via index-of
(define-constant BUFF-TO-BYTE (list
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f
0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f
0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f
0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a 0x3b 0x3c 0x3d 0x3e 0x3f
0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f
0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f
0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e 0x6f
0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b 0x7c 0x7d 0x7e 0x7f
0x80 0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f
0x90 0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f
0xa0 0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf
0xb0 0xb1 0xb2 0xb3 0xb4 0xb5 0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf
0xc0 0xc1 0xc2 0xc3 0xc4 0xc5 0xc6 0xc7 0xc8 0xc9 0xca 0xcb 0xcc 0xcd 0xce 0xcf
0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf
0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef
0xf0 0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff
))
(define-map UintLists
uint ;; size
(list 128 uint) ;; actual list
)
(define-private (get-uint-list (size uint))
(default-to (list ) (map-get? UintLists size))
)
(fold fill-uint-list-closure LONG-UINT-LIST true)
(define-private (fill-uint-list-closure (idx uint) (x bool))
(if (is-eq idx u1)
(map-insert UintLists
idx
(unwrap-panic (as-max-len? (list u1) u128))
)
(map-insert UintLists
idx
(unwrap-panic (as-max-len? (append (unwrap-panic (map-get? UintLists (- idx u1))) idx) u128))
)
)
)
;; define initial token URI
(define-data-var token-uri (optional (string-utf8 256)) (some u"https://cdn.citycoins.co/metadata/citycoin.json"))
;; set token URI to new value, only accessible by CONTRACT-OWNER
(define-public (set-token-uri (new-uri (optional (string-utf8 256))))
(begin
(asserts! (is-eq tx-sender CONTRACT-OWNER) (err ERR-UNAUTHORIZED))
(ok (var-set token-uri new-uri))
)
)
;; Convert a 1-byte buffer into its uint representation.
(define-private (buff-to-u8 (byte (buff 1)))
(unwrap-panic (index-of BUFF-TO-BYTE byte)))
;; Inner fold function for converting a 16-byte buff into a uint.
(define-private (add-and-shift-uint-le (idx uint) (input { acc: uint, data: (buff 16) }))
(let (
(acc (get acc input))
(data (get data input))
(byte (buff-to-u8 (unwrap-panic (element-at data idx))))
)
{
;; acc = byte * (2**(8 * (15 - idx))) + acc
acc: (+ (* byte (pow u2 (* u8 (- u15 idx)))) acc),
data: data
})
)
;; Convert a little-endian 16-byte buff into a uint.
(define-private (buff-to-uint-le (word (buff 16)))
(get acc
(fold add-and-shift-uint-le (list u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15) { acc: u0, data: word })
)
)
;; Inner closure for obtaining the lower 16 bytes of a 32-byte buff
(define-private (lower-16-le-closure (idx uint) (input { acc: (buff 16), data: (buff 32) }))
(let (
(acc (get acc input))
(data (get data input))
(byte (unwrap-panic (element-at data idx)))
)
{
acc: (unwrap-panic (as-max-len? (concat acc byte) u16)),
data: data
})
)
;; Convert the lower 16 bytes of a buff into a little-endian uint.
(define-private (lower-16-le (input (buff 32)))
(get acc
(fold lower-16-le-closure (list u16 u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31) { acc: 0x, data: input })
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; set constant for contract owner, used for updating token-uri
(define-constant CONTRACT-OWNER tx-sender)
;; Mining configuration
(define-constant MINING-ACTIVATION-THRESHOLD u20) ;; how many miners have to register to kickoff countdown to mining activation
(define-data-var mining-activation-threshold uint MINING-ACTIVATION-THRESHOLD) ;; variable used in place of constant for easier testing
(define-data-var mining-activation-threshold-reached bool false) ;; variable used to track if mining is active
(define-constant MINING-ACTIVATION-DELAY u150) ;; how many blocks after last miner registration mining will be activated (~24hrs)
(define-constant MINING-HALVING-BLOCKS u210000) ;; how many blocks until the next halving occurs
(define-data-var miners-nonce uint u0) ;; variable used to generate unique miner-id's
(define-data-var coinbase-threshold-1 uint u0) ;; block height of the 1st halving, set by register-miner
(define-data-var coinbase-threshold-2 uint u0) ;; block height of the 2nd halving, set by register-miner
(define-data-var coinbase-threshold-3 uint u0) ;; block height of the 3rd halving, set by register-miner
(define-data-var coinbase-threshold-4 uint u0) ;; block height of the 4th halving, set by register-miner
(define-data-var coinbase-threshold-5 uint u0) ;; block height of the 5th halving, set by register-miner
;; Stacking configuration, as data vars (so it's easy to test).
(define-data-var first-stacking-block uint FIRST-STACKING-BLOCK)
(define-data-var reward-cycle-length uint REWARD-CYCLE-LENGTH)
(define-data-var token-reward-maturity uint TOKEN-REWARD-MATURITY)
(define-data-var max-reward-cycles uint MAX-REWARD-CYCLES)
;; NOTE: keep this private -- it's used by the test harness to set smaller (easily-tested) values.
(define-private (configure (first-block uint) (rc-len uint) (reward-maturity uint) (max-lockup uint))
(begin
(var-set first-stacking-block first-block)
(var-set reward-cycle-length rc-len)
(var-set token-reward-maturity reward-maturity)
(var-set max-reward-cycles max-lockup)
(ok true)
)
)
(begin
(asserts! (is-eq (len REWARD-CYCLE-INDEXES) MAX-REWARD-CYCLES) (err "Invalid max reward cycles"))
(configure FIRST-STACKING-BLOCK REWARD-CYCLE-LENGTH TOKEN-REWARD-MATURITY MAX-REWARD-CYCLES)
)
;; Bind Stacks block height to a list of up to 128 miners (and how much they mined) per block,
;; and track whether or not the miner has come back to claim their tokens and who mined the least.
(define-map mined-blocks
{ stacks-block-height: uint }
{
miners-count: uint,
least-commitment-idx: uint,
least-commitment-ustx: uint,
claimed: bool,
}
)
(define-map blocks-miners
{ stacks-block-height: uint, idx: uint }
{ miner-id: uint, ustx: uint }
)
;; Maps miner address to uint miner-id
(define-map miners
{ miner: principal }
{ miner-id: uint }
)
;; Returns miner ID if it has been created
(define-read-only (get-miner-id (miner principal))
(get miner-id (map-get? miners { miner: miner }))
)
;; Returns miners ID if it has been created, or creates and returns new
(define-private (get-or-create-miner-id (miner principal))
(match (get miner-id (map-get? miners { miner: miner }))
value value
(let
((new-id (+ u1 (var-get miners-nonce))))
(map-set miners
{ miner: miner }
{ miner-id: new-id}
)
(var-set miners-nonce new-id)
new-id
)
)
)
;; TO DO: think about adding amount to mined-blocks map.
(define-map block-commit
{ stacks-block-height: uint }
{ amount: uint,
amount-to-stackers: uint,
amount-to-city: uint
}
)
(define-map miners-block-commitment
{ miner-id: uint, stacks-block-height: uint }
{ committed: bool }
)
;; How many uSTX are mined per reward cycle, and how many tokens are locked up in the same reward cycle.
(define-map tokens-per-cycle
{ reward-cycle: uint }
{ total-ustx: uint, total-tokens: uint }
)
;; Who has locked up how many tokens for a given reward cycle.
(define-map stacked-per-cycle
{ stacker: principal, reward-cycle: uint }
{ amount-token: uint }
)
;; The fungible token that can be Stacked.
(define-fungible-token resonancetoken u10000000)
(define-public (register-miner (memo (optional (buff 34))))
(let
(
(new-id (+ u1 (var-get miners-nonce)))
(threshold (var-get mining-activation-threshold))
)
(asserts! (is-none (map-get? miners { miner: tx-sender }))
(err ERR-MINER-ALREADY-REGISTERED))
(asserts! (<= new-id threshold)
(err ERR-MINING-ACTIVATION-THRESHOLD-REACHED))
(if (is-some memo)
(print memo)
none
)
(map-set miners
{ miner: tx-sender }
{ miner-id: new-id }
)
(var-set miners-nonce new-id)
(if (is-eq new-id threshold)
(let
(
(first-stacking-block-val (+ block-height MINING-ACTIVATION-DELAY))
)
(var-set mining-activation-threshold-reached true)
(var-set first-stacking-block first-stacking-block-val)
(var-set coinbase-threshold-1 (+ first-stacking-block-val MINING-HALVING-BLOCKS))
(var-set coinbase-threshold-2 (+ first-stacking-block-val (* u2 MINING-HALVING-BLOCKS)))
(var-set coinbase-threshold-3 (+ first-stacking-block-val (* u3 MINING-HALVING-BLOCKS)))
(var-set coinbase-threshold-4 (+ first-stacking-block-val (* u4 MINING-HALVING-BLOCKS)))
(var-set coinbase-threshold-5 (+ first-stacking-block-val (* u5 MINING-HALVING-BLOCKS)))
(ok true)
)
(ok true)
)
)
)
;; Getter for checking if mining is activated
(define-read-only (get-mining-activation-status)
(var-get mining-activation-threshold-reached)
)
;; Getter for current registration threshold
(define-read-only (get-registered-miners-threshold)
(var-get mining-activation-threshold)
)
(define-read-only (get-registered-miners-nonce)
(var-get miners-nonce)
)
;; Function for deciding how many tokens to mint, depending on when they were mined.
(define-read-only (get-coinbase-amount (miner-block-height uint))
(let
(
;; set a new variable to make things easier to read
(activation-block-height (var-get first-stacking-block))
)
;; determine if mining was active, return 0 if not
(asserts! (>= miner-block-height activation-block-height) u0)
;; evaluate current block height against issuance schedule and return correct coinbase amount
;; halvings occur every 210,000 blocks for 1,050,000 Stacks blocks
;; then mining continues indefinitely with 3,125 CityCoins as the reward
(asserts! (> miner-block-height (var-get coinbase-threshold-1))
(if (<= (- miner-block-height activation-block-height) u10000)
u250000 ;; bonus reward first 10,000 blocks
u100000 ;; standard reward remaining 200,000 blocks until 1st halving
)
)
(asserts! (> miner-block-height (var-get coinbase-threshold-2)) u50000) ;; between 1st and 2nd halving u50000
(asserts! (> miner-block-height (var-get coinbase-threshold-3)) u25000) ;; between 2nd and 3rd halving u25000
(asserts! (> miner-block-height (var-get coinbase-threshold-4)) u12500) ;; between 3rd and 4th halving u12500
(asserts! (> miner-block-height (var-get coinbase-threshold-5)) u6250) ;; between 4th and 5th halving u6250
;; default value after 5th halving
u3125
)
)
;; Getter for getting the list of miners and uSTX committments for a given block.
(define-read-only (get-miners-at-block (stacks-block-height uint))
(get miners (fold
get-miners-at-block-closure
(get-uint-list (get miners-count (get-mined-block-or-default stacks-block-height)))
{ stacks-block-height: stacks-block-height, miners: (list )}
))
)
(define-private (get-miners-at-block-closure (idx uint) (data { stacks-block-height: uint, miners: (list 128 { miner-id: uint, ustx: uint })}))
(match (map-get? blocks-miners { stacks-block-height: (get stacks-block-height data), idx: idx })
miner
{
stacks-block-height: (get stacks-block-height data),
miners: (unwrap-panic (as-max-len? (append (get miners data) miner) u128))
}
data
)
)
;; Getter for getting how many tokens are Stacked by the given principal in the given reward cycle.
(define-read-only (get-stacked-in-cycle (stacker principal) (reward-cycle uint))
(match (map-get? stacked-per-cycle { stacker: stacker, reward-cycle: reward-cycle })
stacked-rec (get amount-token stacked-rec)
u0
)
)
;; Getter for getting how many uSTX are committed and tokens are Stacked per reward cycle.
(define-read-only (get-tokens-per-cycle (rc uint))
(match (map-get? tokens-per-cycle { reward-cycle: rc })
token-info token-info
{ total-ustx: u0, total-tokens: u0 }
)
)
;; API endpoint for getting statistics about this PoX-lite contract.
;; Compare to /v2/pox on the Stacks node.
(define-read-only (get-pox-lite-info)
(match (get-reward-cycle block-height)
cur-reward-cycle
(ok
(let (
(token-info (get-tokens-per-cycle cur-reward-cycle))
(total-ft-supply (ft-get-supply citycoins))
(total-ustx-supply (stx-get-balance (as-contract tx-sender)))
)
{
reward-cycle-id: cur-reward-cycle,
first-block-height: (var-get first-stacking-block),
reward-cycle-length: (var-get reward-cycle-length),
total-supply: total-ft-supply,
total-ustx-locked: total-ustx-supply,
cur-liquid-supply: (- total-ft-supply (get total-tokens token-info)),
cur-locked-supply: (get total-tokens token-info),
cur-ustx-committed: (get total-ustx token-info)
})
)
(err ERR-STACKING-NOT-AVAILABLE)
)
)
;; Produce the new tokens for the given claimant, who won the tokens at the given Stacks block height.
(define-private (mint-coinbase (recipient principal) (stacks-block-ht uint))
(ft-mint? citycoins (get-coinbase-amount stacks-block-ht) recipient)
)
;; Getter to obtain the list of miners and uSTX commitments at a given Stacks block height,
;; OR, an empty such structure.
(define-private (get-mined-block-or-default (stacks-block-height uint))
(match (map-get? mined-blocks { stacks-block-height: stacks-block-height })
block block
{
miners-count: u0,
least-commitment-idx: u0,
least-commitment-ustx: u0,
claimed: false,
})
)
;; Given stacks-block-height, return how many uSTX were committed in total
(define-read-only (get-block-commit-total (stacks-block-height uint))
(default-to u0 (get amount (map-get? block-commit {stacks-block-height: stacks-block-height})))
)
;; Given stacks-block-height, return how many uSTX were committed to stackers
(define-read-only (get-block-commit-to-stackers (stacks-block-height uint))
(default-to u0 (get amount-to-stackers (map-get? block-commit {stacks-block-height: stacks-block-height})))
)
;; Given stacks-block-height, return how many uSTX were committed to the city
(define-read-only (get-block-commit-to-city (stacks-block-height uint))
(default-to u0 (get amount-to-city (map-get? block-commit {stacks-block-height: stacks-block-height})))
)
;; Inner fold function to determine which miner won the token batch at a particular Stacks block height, given a sampling value.
(define-private (get-block-winner-closure (idx uint) (data { stacks-block-height: uint, sample: uint, sum: uint, winner: (optional { miner-id: uint, ustx: uint})}))
(match (map-get? blocks-miners { stacks-block-height: (get stacks-block-height data), idx: idx})
miner
(let
(
(sum (get sum data))
(sample (get sample data))
(ustx (get ustx miner))
(next-sum (+ sum ustx))
(new-winner
(if (and (>= sample sum) (< sample next-sum))
(some miner)
(get winner data)
)
)
)
{
stacks-block-height: (get stacks-block-height data),
sample: sample,
sum: next-sum,
winner: new-winner
}
)
data
)
)
;; Determine who won a given batch of tokens, given a random sample and a list of miners and commitments.
;; The probability that a given miner wins the batch is proportional to how many uSTX it committed out of the
;; sum of commitments for this block.
(define-read-only (get-block-winner (stacks-block-height uint) (random-sample uint))
(let
(
(commit-total (get-block-commit-total stacks-block-height))
)
(if (> commit-total u0)
(get winner (fold
get-block-winner-closure
(get-uint-list (get miners-count (get-mined-block-or-default stacks-block-height)))
{
stacks-block-height: stacks-block-height,
sample: (mod random-sample commit-total),
sum: u0,
winner: none
}
))
none
)
)
)
;; Determine if a given miner has already mined at given block height
(define-read-only (has-mined (miner-id uint) (stacks-block-height uint))
(is-some (map-get? miners-block-commitment
{ miner-id: miner-id, stacks-block-height: stacks-block-height }
))
)
;; Determine whether or not the given principal can claim the mined tokens at a particular block height,
;; given the miners record for that block height, a random sample, and the current block height.
(define-read-only (can-claim-tokens (claimer principal)
(claimer-stacks-block-height uint)
(random-sample uint)
(block {
miners-count: uint,
least-commitment-idx: uint,
least-commitment-ustx: uint,
claimed: bool
})
(current-stacks-block uint))
(let (
(claimer-id (unwrap! (get-miner-id claimer) (err ERR-MINER-ID-NOT-FOUND)))
(reward-maturity (var-get token-reward-maturity))
(maximum-stacks-block-height
(if (>= current-stacks-block reward-maturity)
(- current-stacks-block reward-maturity)
u0))
)
(if (< claimer-stacks-block-height maximum-stacks-block-height)
(begin
(asserts! (not (get claimed block))
(err ERR-ALREADY-CLAIMED))
(match (get-block-winner claimer-stacks-block-height random-sample)
winner-rec (if (is-eq claimer-id (get miner-id winner-rec))
(ok true)
(err ERR-UNAUTHORIZED))
(err ERR-NO-WINNER))
)
(err ERR-IMMATURE-TOKEN-REWARD)))
)
;; Mark a batch of mined tokens as claimed, so no one else can go and claim them.
(define-private (set-tokens-claimed (claimed-stacks-block-height uint))
(let (
(miner-rec (unwrap!
(map-get? mined-blocks { stacks-block-height: claimed-stacks-block-height })
(err ERR-NO-WINNER)))
)
(begin
(asserts! (not (get claimed miner-rec))
(err ERR-ALREADY-CLAIMED))
(map-set mined-blocks
{ stacks-block-height: claimed-stacks-block-height }
(merge miner-rec { claimed: true })
)
(ok true)))
)
;; Determine whether or not the given miner can actually mine tokens right now.
;; * Stacking must be active for this smart contract
;; * No more than 31 miners must have mined already
;; * This miner hasn't mined in this block before
;; * The miner is committing a positive number of uSTX
;; * The miner has the uSTX to commit
(define-read-only (can-mine-tokens (miner principal) (miner-id uint) (stacks-block-height uint) (amount-ustx uint))
(let
(
(block (get-mined-block-or-default stacks-block-height))
)
(if (and (is-eq MAX-MINERS-COUNT (get miners-count block)) (<= amount-ustx (get least-commitment-ustx block)))
(err ERR-TOO-SMALL-COMMITMENT)
(begin
(asserts! (is-some (get-reward-cycle stacks-block-height))
(err ERR-STACKING-NOT-AVAILABLE))
(asserts! (not (has-mined miner-id stacks-block-height))
(err ERR-ALREADY-MINED))
(asserts! (> amount-ustx u0)
(err ERR-CANNOT-MINE))
(asserts! (>= (stx-get-balance miner) amount-ustx)
(err ERR-INSUFFICIENT-BALANCE))
(ok true)
)
)
)
)
;; Determine if a Stacker can Stack their tokens. Like PoX, they must supply
;; a future Stacks block height at which Stacking begins, as well as a lock-up period
;; in reward cycles.
;; * The Stacker's start block height must be in the future
;; * The first reward cycle must be _after_ the current reward cycle
;; * The lock period must be valid (positive, but no greater than the maximum allowed period)
;; * The Stacker must have tokens to Stack.
(define-read-only (can-stack-tokens (stacker principal) (amount-tokens uint) (now-stacks-ht uint) (start-stacks-ht uint) (lock-period uint))
(let (
(cur-reward-cycle (unwrap! (get-reward-cycle now-stacks-ht) (err ERR-STACKING-NOT-AVAILABLE)))
(start-reward-cycle (+ u1 (unwrap! (get-reward-cycle start-stacks-ht) (err ERR-STACKING-NOT-AVAILABLE))))
(max-lockup (var-get max-reward-cycles))
)
(begin
(asserts! (< now-stacks-ht start-stacks-ht)
(err ERR-CANNOT-STACK))
(asserts! (and (> lock-period u0) (<= lock-period max-lockup))
(err ERR-CANNOT-STACK))
(asserts! (> amount-tokens u0)
(err ERR-CANNOT-STACK))
(asserts! (<= amount-tokens (ft-get-balance citycoins stacker))
(err ERR-INSUFFICIENT-BALANCE))
(ok true)
))
)
;; Determine how many uSTX a Stacker is allowed to claim, given the reward cycle they Stacked in and the current block height.
;; This method only returns a positive value if:
;; * The current block height is in a subsequent reward cycle
;; * The Stacker actually did lock up some tokens in the target reward cycle
;; * The Stacker locked up _enough_ tokens to get at least one uSTX.
;; It's possible to Stack tokens but not receive uSTX. For example, no miners may have mined in this reward cycle.
;; As another example, you may have Stacked so few that you'd be entitled to less than 1 uSTX.
(define-read-only (get-entitled-stacking-reward (stacker principal) (target-reward-cycle uint) (cur-block-height uint))
(let (
(stacked-this-cycle
(get amount-token
(default-to { amount-token: u0 }
(map-get? stacked-per-cycle { stacker: stacker, reward-cycle: target-reward-cycle }))))
(total-tokens-this-cycle
(default-to { total-ustx: u0, total-tokens: u0 }
(map-get? tokens-per-cycle { reward-cycle: target-reward-cycle })))
)
(match (get-reward-cycle cur-block-height)
cur-reward-cycle
(if (or (<= cur-reward-cycle target-reward-cycle) (is-eq u0 (get total-tokens total-tokens-this-cycle)))
;; either this reward cycle hasn't finished yet, or the Stacker contributed nothing
u0
;; (total-ustx * this-stackers-tokens) / total-tokens-stacked
(/ (* (get total-ustx total-tokens-this-cycle) stacked-this-cycle)
(get total-tokens total-tokens-this-cycle))
)
;; before first reward cycle
u0
))
)
;; Helper variable used only to achieve "dynamic" filter condition in closure function called by `filter`
(define-data-var miner-to-kick (optional {miner-id: uint, amount-ustx: uint}) none)
;; Inner filter function.
;; Returns true if supplied miner in not miner who committed the least and needs to be kicked out of the list
(define-private (remove-miner-to-kick-closure (miner-data {miner-id: uint, amount-ustx: uint}))
(not
(is-eq miner-data (unwrap-panic (var-get miner-to-kick)))
)
)
(define-private (find-least (miner-data {miner-id: uint, amount-ustx: uint})
(ret-data (optional {miner-id: uint, amount-ustx: uint})))
(if (is-some ret-data)
(if ( < (get amount-ustx miner-data) (default-to u0 (get amount-ustx ret-data)))
(some miner-data)
ret-data
)
(some miner-data)
)
)
;; Mark a miner as having mined in a given Stacks block and committed the given uSTX.
(define-private (set-tokens-mined (miner principal) (miner-id uint) (stacks-block-height uint) (commit-ustx uint) (commit-ustx-to-stackers uint) (commit-ustx-to-city uint))
(let (
(block (get-mined-block-or-default stacks-block-height))
(increased-miners-count (+ (get miners-count block) u1))
(new-idx increased-miners-count)
(least-commitment-idx (get least-commitment-idx block))
(least-commitment-ustx (get least-commitment-ustx block))
(reward-cycle (unwrap! (get-reward-cycle stacks-block-height)
(err ERR-STACKING-NOT-AVAILABLE)))
(tokens-mined (default-to { total-ustx: u0, total-tokens: u0 }
(map-get? tokens-per-cycle { reward-cycle: reward-cycle }))
)
)
(begin
(if (> MAX-MINERS-COUNT (get miners-count block))
(begin
;; list is not full - add new miner and calculate if he committed the least
(map-set blocks-miners
{ stacks-block-height: stacks-block-height, idx: new-idx }
{ miner-id: miner-id, ustx: commit-ustx }
)
(map-set mined-blocks
{ stacks-block-height: stacks-block-height }
{
miners-count: increased-miners-count,
least-commitment-idx: (if (or (is-eq new-idx u1) (< commit-ustx least-commitment-ustx)) new-idx least-commitment-idx),
least-commitment-ustx: (if (or (is-eq new-idx u1) (< commit-ustx least-commitment-ustx)) commit-ustx least-commitment-ustx),
claimed: false
}
)
)
(begin
;; list is full - replace miner who committed the least with new one and calculate new miner who committed the least
(map-set blocks-miners
{ stacks-block-height: stacks-block-height, idx: least-commitment-idx }
{ miner-id: miner-id, ustx: commit-ustx }
)
(let
(
(least-commitment (find-least-commitment stacks-block-height))
)
(map-set mined-blocks
{ stacks-block-height: stacks-block-height }
{
miners-count: MAX-MINERS-COUNT,
least-commitment-idx: (get least-commitment-idx least-commitment),
least-commitment-ustx: (get least-commitment-ustx least-commitment),
claimed: false
}
)
)
)
)
(map-set miners-block-commitment
{ miner-id: miner-id, stacks-block-height: stacks-block-height}
{ committed: true }
)
(map-set tokens-per-cycle
{ reward-cycle: reward-cycle }
{ total-ustx: (+ commit-ustx-to-stackers (get total-ustx tokens-mined)), total-tokens: (get total-tokens tokens-mined) }
)
(map-set block-commit
{ stacks-block-height: stacks-block-height }
{
amount: (+ commit-ustx (get-block-commit-total stacks-block-height)),
amount-to-stackers: (+ commit-ustx-to-stackers (get-block-commit-to-stackers stacks-block-height)),
amount-to-city: (+ commit-ustx-to-city (get-block-commit-to-city stacks-block-height))
}
)
(ok true)
))
)
(define-read-only (find-least-commitment (stacks-block-height uint))
(fold find-least-commitment-closure LONG-UINT-LIST { stacks-block-height: stacks-block-height, least-commitment-idx: u0, least-commitment-ustx: u0 })
)
(define-private (find-least-commitment-closure (idx uint) (data { stacks-block-height: uint, least-commitment-idx: uint, least-commitment-ustx: uint }))
(match (get ustx (map-get? blocks-miners { stacks-block-height: (get stacks-block-height data), idx: idx }))
ustx
(if (or (is-eq idx u1) (< ustx (get least-commitment-ustx data)))
{
stacks-block-height: (get stacks-block-height data),
least-commitment-idx: (if (> ustx u0) idx u0), ;; if is used here to return 0 when called on block without miners
least-commitment-ustx: ustx
}
data
)
data
)
)
;; Get the reward cycle for a given Stacks block height
(define-read-only (get-reward-cycle (stacks-bh uint))
(let (
(first-stack-block (var-get first-stacking-block))
(rc-len (var-get reward-cycle-length))
)
(if (>= stacks-bh first-stack-block)
(some (/ (- stacks-bh first-stack-block) rc-len))
none
))
)
;; Get the first Stacks block height for a given reward cycle.
(define-read-only (get-first-block-height-in-reward-cycle (reward-cycle uint))
(+ (var-get first-stacking-block) (* (var-get reward-cycle-length) reward-cycle)))
;; Read the on-chain VRF and turn the lower 16 bytes into a uint, in order to sample the set of miners and determine
;; which one may claim the token batch for the given block height.
(define-read-only (get-random-uint-at-block (stacks-block uint))
(let (
(vrf-lower-uint-opt
(match (get-block-info? vrf-seed stacks-block)
vrf-seed (some (buff-to-uint-le (lower-16-le vrf-seed)))
none))
)
vrf-lower-uint-opt)
)
;; Inner fold function for Stacking tokens. Populates the stacked-per-cycle and tokens-per-cycle tables for each
;; reward cycle the Stacker is Stacking in.
(define-private (stack-tokens-closure (reward-cycle-idx uint) (commitment { stacker: principal, amt: uint, first: uint, last: uint }))
(let (
(stacker (get stacker commitment))
(amount-token (get amt commitment))
(first-reward-cycle (get first commitment))
(last-reward-cycle (get last commitment))
(target-reward-cycle (+ first-reward-cycle reward-cycle-idx))
(stacked-already (match (map-get? stacked-per-cycle { stacker: stacker, reward-cycle: target-reward-cycle })
rec (get amount-token rec)
u0))
(tokens-this-cycle (match (map-get? tokens-per-cycle { reward-cycle: target-reward-cycle })
rec rec
{ total-ustx: u0, total-tokens: u0 }))
)
(begin
(if (and (>= target-reward-cycle first-reward-cycle) (< target-reward-cycle last-reward-cycle))
(begin
(map-set stacked-per-cycle
{ stacker: stacker, reward-cycle: target-reward-cycle }
{ amount-token: (+ amount-token stacked-already) })
(map-set tokens-per-cycle
{ reward-cycle: target-reward-cycle }
{ total-ustx: (get total-ustx tokens-this-cycle), total-tokens: (+ amount-token (get total-tokens tokens-this-cycle)) })
true)
false)
{ stacker: stacker, amt: amount-token, first: first-reward-cycle, last: last-reward-cycle }
))
)
;; Stack the contract's tokens. Stacking will begin at the next reward cycle following
;; the reward cycle in which start-stacks-ht resides.
;; This method takes possession of the Stacker's tokens until the given number of reward cycles
;; has passed.
(define-public (stack-tokens (amount-tokens uint) (start-stacks-ht uint) (lock-period uint))
(let (
(start-reward-cycle (+ u1 (unwrap! (get-reward-cycle start-stacks-ht) (err ERR-STACKING-NOT-AVAILABLE))))
)
(begin
(try! (can-stack-tokens tx-sender amount-tokens block-height start-stacks-ht lock-period))
(unwrap! (ft-transfer? citycoins amount-tokens tx-sender (as-contract tx-sender))
(err ERR-INSUFFICIENT-BALANCE))
(fold stack-tokens-closure REWARD-CYCLE-INDEXES
{ stacker: tx-sender, amt: amount-tokens, first: start-reward-cycle, last: (+ start-reward-cycle lock-period) })
(ok true)
))
)
;; Mine tokens. The miner commits uSTX into this contract (which Stackers can claim later with claim-stacking-reward),
;; and in doing so, enters their candidacy to be able to claim the block reward (via claim-token-reward). The miner must
;; wait for a token maturity window in order to obtain the tokens. Once that window passes, they can get the tokens.
;; This ensures that no one knows the VRF seed that will be used to pick the winner.
(define-public (mine-tokens (amount-ustx uint) (memo (optional (buff 34))))
(begin
(if (is-some memo)
(print memo)
none
)
(mine-tokens-at-block block-height (get-or-create-miner-id tx-sender) amount-ustx)
)
)
(define-public (mine-tokens-over-5-blocks (amount-ustx uint))
(let
((miner-id (get-or-create-miner-id tx-sender)))
(asserts! (>= (stx-get-balance tx-sender) (* u5 amount-ustx))
(err ERR-INSUFFICIENT-BALANCE))
(try! (mine-tokens-at-block block-height miner-id amount-ustx))
(try! (mine-tokens-at-block (+ block-height u1) miner-id amount-ustx))
(try! (mine-tokens-at-block (+ block-height u2) miner-id amount-ustx))
(try! (mine-tokens-at-block (+ block-height u3) miner-id amount-ustx))
(try! (mine-tokens-at-block (+ block-height u4) miner-id amount-ustx))
(ok true)
)
)
(define-private (mine-tokens-at-block (stacks-block-height uint) (miner-id uint) (amount-ustx uint))
(let (
(rc (unwrap! (get-reward-cycle stacks-block-height)
(err ERR-STACKING-NOT-AVAILABLE)))
(total-stacked (get total-tokens (map-get? tokens-per-cycle { reward-cycle: rc })))
(total-stacked-ustx (default-to u0 total-stacked))
(stacked-something (not (is-eq total-stacked-ustx u0)))
(amount-ustx-to-stacker
(if stacked-something
(/ (* SPLIT_STACKER_PERCENTAGE amount-ustx) u100)
u0
)
)
(amount-ustx-to-city
(if stacked-something
(/ (* SPLIT_CITY_PERCENTAGE amount-ustx) u100)
amount-ustx
)
)
)
(begin
(try! (can-mine-tokens tx-sender miner-id stacks-block-height amount-ustx))
(try! (set-tokens-mined tx-sender miner-id stacks-block-height amount-ustx amount-ustx-to-stacker amount-ustx-to-city))
;; check if stacking is active
(if stacked-something
;; transfer with split if active
(begin
(unwrap-panic (stx-transfer? amount-ustx-to-stacker tx-sender (as-contract tx-sender)))
(unwrap-panic (stx-transfer? amount-ustx-to-city tx-sender (var-get city-wallet)))
)
;; transfer to custodied wallet if not active
(unwrap-panic (stx-transfer? amount-ustx-to-city tx-sender (var-get city-wallet)))
)
(ok true)
))
)
;; Claim the block reward. This mints and transfers out a miner's tokens if it is indeed the block winner for
;; the given Stacks block. The VRF seed will be sampled at the target mined stacks block height _plus_ the
;; maturity window, and if the miner (i.e. the caller of this function) both mined in the target Stacks block
;; and was later selected by the VRF as the winner, they will receive that block's token batch.
;; Note that this method actually mints the contract's tokens -- they do not exist until the miner calls
;; this method.
(define-public (claim-token-reward (mined-stacks-block-ht uint))
(let (
(random-sample (unwrap! (get-random-uint-at-block (+ mined-stacks-block-ht (var-get token-reward-maturity)))
(err ERR-IMMATURE-TOKEN-REWARD)))
(block (unwrap! (map-get? mined-blocks { stacks-block-height: mined-stacks-block-ht })
(err ERR-NO-WINNER)))
)
(begin
(try! (can-claim-tokens tx-sender mined-stacks-block-ht random-sample block block-height))
(try! (set-tokens-claimed mined-stacks-block-ht))
(unwrap-panic (mint-coinbase tx-sender mined-stacks-block-ht))
(ok true)
))
)
;; Claim a Stacking reward. Once a reward cycle passes, a Stacker can call this method to obtain any
;; uSTX that were committed to the contract during that reward cycle (proportional to how many tokens
;; they locked up).
(define-public (claim-stacking-reward (target-reward-cycle uint))
(let (
(stacker tx-sender)
(entitled-ustx (get-entitled-stacking-reward tx-sender target-reward-cycle block-height))
(stacked-in-cycle (get-stacked-in-cycle tx-sender target-reward-cycle))
)
(begin
(asserts! (> entitled-ustx u0)
(err ERR-NOTHING-TO-REDEEM))
;; can't claim again
(map-set stacked-per-cycle
{ stacker: tx-sender, reward-cycle: target-reward-cycle }
{ amount-token: u0 })
(try! (as-contract (stx-transfer? entitled-ustx tx-sender stacker)))
(try! (as-contract (ft-transfer? citycoins stacked-in-cycle tx-sender stacker)))
(ok true)
))
)
(define-read-only (get-total-supply-ustx)
(ok (stx-get-balance (as-contract tx-sender)))
)
(define-read-only (get-city-wallet)
(var-get city-wallet)
)
;; Update the city-wallet variable
;; This can only be called by the city-wallet principal.
;; Calling `set-city-wallet` from an outside contract (that is not the city-wallet principal)
;; is not allowed
(define-public (set-city-wallet (wallet-address principal))
(begin
(asserts! (is-eq contract-caller (var-get city-wallet)) (err ERR-UNAUTHORIZED))
(ok (var-set city-wallet wallet-address))
)
)
;;;;;;;;;;;;;;;;;;;;; SIP 010 ;;;;;;;;;;;;;;;;;;;;;;
;; testnet: (impl-trait 'STR8P3RD1EHA8AA37ERSSSZSWKS9T2GYQFGXNA4C.sip-010-trait-ft-standard.sip-010-trait)
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait)
(define-public (transfer (amount uint) (from principal) (to principal) (memo (optional (buff 34))))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(if (is-some memo)
(print memo)
none
)
(ft-transfer? citycoins amount from to)
)
)
(define-read-only (get-name)
(ok "citycoins"))
(define-read-only (get-symbol)
(ok "CYCN"))
(define-read-only (get-decimals)
(ok u0))
(define-read-only (get-balance (user principal))
(ok (ft-get-balance citycoins user)))
(define-read-only (get-total-supply)
(ok (ft-get-supply citycoins)))
(define-read-only (get-token-uri)
(ok (var-get token-uri))) | 0x07f647425f1bebaee230347e64cfc700c0e58df9d8fae82779f9f081615c0b7b | 19,193 | abort_by_response |
dmt-mine | ;; error codes
(define-constant ERR-NO-WINNER u0)
(define-constant ERR-NO-SUCH-MINER u1)
(define-constant ERR-IMMATURE-TOKEN-REWARD u2)
(define-constant ERR-UNAUTHORIZED u3)
(define-constant ERR-ALREADY-CLAIMED u4)
(define-constant ERR-STACKING-NOT-AVAILABLE u5)
(define-constant ERR-CANNOT-STACK u6)
(define-constant ERR-INSUFFICIENT-BALANCE u7)
(define-constant ERR-ALREADY-MINED u8)
(define-constant ERR-ROUND-FULL u9) ;; deprecated - this error is not used anymore
(define-constant ERR-NOTHING-TO-REDEEM u10)
(define-constant ERR-CANNOT-MINE u11)
(define-constant ERR-MINER-ALREADY-REGISTERED u12)
(define-constant ERR-MINING-ACTIVATION-THRESHOLD-REACHED u13)
(define-constant ERR-MINER-ID-NOT-FOUND u14)
(define-constant ERR-TOO-SMALL-COMMITMENT u15)
;; Tailor to your needs.
(define-constant TOKEN-REWARD-MATURITY u5) ;; how long a miner must wait before claiming their minted tokens
(define-constant FIRST-STACKING-BLOCK u340282366920938463463374607431768211455) ;; Stacks block height when Stacking is available
(define-constant REWARD-CYCLE-LENGTH u2100) ;; how long a reward cycle is
(define-constant MAX-REWARD-CYCLES u32) ;; how many reward cycles a Stacker can Stack their tokens for
(define-constant MAX-MINERS-COUNT u128) ;; maximum amount of miners in one block
(define-constant LONG-UINT-LIST (list
u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15 u16
u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31 u32
u33 u34 u35 u36 u37 u38 u39 u40 u41 u42 u43 u44 u45 u46 u47 u48
u49 u50 u51 u52 u53 u54 u55 u56 u57 u58 u59 u60 u61 u62 u63 u64
u65 u66 u67 u68 u69 u70 u71 u72 u73 u74 u75 u76 u77 u78 u79 u80
u81 u82 u83 u84 u85 u86 u87 u88 u89 u90 u91 u92 u93 u94 u95 u96
u97 u98 u99 u100 u101 u102 u103 u104 u105 u106 u107 u108 u109 u110 u111 u112
u113 u114 u115 u116 u117 u118 u119 u120 u121 u122 u123 u124 u125 u126 u127 u128
))
;; Define city wallet and mining split
(define-constant CITY_CUSTODIED_WALLET 'ST31270FK25JBGCRWYT7RNK90E946R8VW6SZYSQR6) ;; the custodied wallet address for the city
(define-data-var city-wallet principal CITY_CUSTODIED_WALLET) ;; variable used in place of constant for easier testing
(define-constant SPLIT_STACKER_PERCENTAGE u70) ;; 70% split to stackers of the CityCoin
(define-constant SPLIT_CITY_PERCENTAGE u30) ;; 30% split to custodied wallet address for the city
;; NOTE: must be as long as MAX-REWARD-CYCLES
(define-constant REWARD-CYCLE-INDEXES (list u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15 u16 u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31))
;; lookup table for converting 1-byte buffers to uints via index-of
(define-constant BUFF-TO-BYTE (list
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f
0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f
0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f
0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a 0x3b 0x3c 0x3d 0x3e 0x3f
0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f
0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f
0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e 0x6f
0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b 0x7c 0x7d 0x7e 0x7f
0x80 0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f
0x90 0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f
0xa0 0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf
0xb0 0xb1 0xb2 0xb3 0xb4 0xb5 0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf
0xc0 0xc1 0xc2 0xc3 0xc4 0xc5 0xc6 0xc7 0xc8 0xc9 0xca 0xcb 0xcc 0xcd 0xce 0xcf
0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf
0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef
0xf0 0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff
))
(define-map UintLists
uint ;; size
(list 128 uint) ;; actual list
)
(define-private (get-uint-list (size uint))
(default-to (list ) (map-get? UintLists size))
)
(fold fill-uint-list-closure LONG-UINT-LIST true)
(define-private (fill-uint-list-closure (idx uint) (x bool))
(if (is-eq idx u1)
(map-insert UintLists
idx
(unwrap-panic (as-max-len? (list u1) u128))
)
(map-insert UintLists
idx
(unwrap-panic (as-max-len? (append (unwrap-panic (map-get? UintLists (- idx u1))) idx) u128))
)
)
)
;; define initial token URI
(define-data-var token-uri (optional (string-utf8 256)) (some u"https://cdn.citycoins.co/metadata/citycoin.json"))
;; set token URI to new value, only accessible by CONTRACT-OWNER
(define-public (set-token-uri (new-uri (optional (string-utf8 256))))
(begin
(asserts! (is-eq tx-sender CONTRACT-OWNER) (err ERR-UNAUTHORIZED))
(ok (var-set token-uri new-uri))
)
)
;; Convert a 1-byte buffer into its uint representation.
(define-private (buff-to-u8 (byte (buff 1)))
(unwrap-panic (index-of BUFF-TO-BYTE byte)))
;; Inner fold function for converting a 16-byte buff into a uint.
(define-private (add-and-shift-uint-le (idx uint) (input { acc: uint, data: (buff 16) }))
(let (
(acc (get acc input))
(data (get data input))
(byte (buff-to-u8 (unwrap-panic (element-at data idx))))
)
{
;; acc = byte * (2**(8 * (15 - idx))) + acc
acc: (+ (* byte (pow u2 (* u8 (- u15 idx)))) acc),
data: data
})
)
;; Convert a little-endian 16-byte buff into a uint.
(define-private (buff-to-uint-le (word (buff 16)))
(get acc
(fold add-and-shift-uint-le (list u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15) { acc: u0, data: word })
)
)
;; Inner closure for obtaining the lower 16 bytes of a 32-byte buff
(define-private (lower-16-le-closure (idx uint) (input { acc: (buff 16), data: (buff 32) }))
(let (
(acc (get acc input))
(data (get data input))
(byte (unwrap-panic (element-at data idx)))
)
{
acc: (unwrap-panic (as-max-len? (concat acc byte) u16)),
data: data
})
)
;; Convert the lower 16 bytes of a buff into a little-endian uint.
(define-private (lower-16-le (input (buff 32)))
(get acc
(fold lower-16-le-closure (list u16 u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31) { acc: 0x, data: input })
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; set constant for contract owner, used for updating token-uri
(define-constant CONTRACT-OWNER tx-sender)
;; Mining configuration
(define-constant MINING-ACTIVATION-THRESHOLD u20) ;; how many miners have to register to kickoff countdown to mining activation
(define-data-var mining-activation-threshold uint MINING-ACTIVATION-THRESHOLD) ;; variable used in place of constant for easier testing
(define-data-var mining-activation-threshold-reached bool false) ;; variable used to track if mining is active
(define-constant MINING-ACTIVATION-DELAY u150) ;; how many blocks after last miner registration mining will be activated (~24hrs)
(define-constant MINING-HALVING-BLOCKS u210000) ;; how many blocks until the next halving occurs
(define-data-var miners-nonce uint u0) ;; variable used to generate unique miner-id's
(define-data-var coinbase-threshold-1 uint u0) ;; block height of the 1st halving, set by register-miner
(define-data-var coinbase-threshold-2 uint u0) ;; block height of the 2nd halving, set by register-miner
(define-data-var coinbase-threshold-3 uint u0) ;; block height of the 3rd halving, set by register-miner
(define-data-var coinbase-threshold-4 uint u0) ;; block height of the 4th halving, set by register-miner
(define-data-var coinbase-threshold-5 uint u0) ;; block height of the 5th halving, set by register-miner
;; Stacking configuration, as data vars (so it's easy to test).
(define-data-var first-stacking-block uint FIRST-STACKING-BLOCK)
(define-data-var reward-cycle-length uint REWARD-CYCLE-LENGTH)
(define-data-var token-reward-maturity uint TOKEN-REWARD-MATURITY)
(define-data-var max-reward-cycles uint MAX-REWARD-CYCLES)
;; NOTE: keep this private -- it's used by the test harness to set smaller (easily-tested) values.
(define-private (configure (first-block uint) (rc-len uint) (reward-maturity uint) (max-lockup uint))
(begin
(var-set first-stacking-block first-block)
(var-set reward-cycle-length rc-len)
(var-set token-reward-maturity reward-maturity)
(var-set max-reward-cycles max-lockup)
(ok true)
)
)
(begin
(asserts! (is-eq (len REWARD-CYCLE-INDEXES) MAX-REWARD-CYCLES) (err "Invalid max reward cycles"))
(configure FIRST-STACKING-BLOCK REWARD-CYCLE-LENGTH TOKEN-REWARD-MATURITY MAX-REWARD-CYCLES)
)
;; Bind Stacks block height to a list of up to 128 miners (and how much they mined) per block,
;; and track whether or not the miner has come back to claim their tokens and who mined the least.
(define-map mined-blocks
{ stacks-block-height: uint }
{
miners-count: uint,
least-commitment-idx: uint,
least-commitment-ustx: uint,
claimed: bool,
}
)
(define-map blocks-miners
{ stacks-block-height: uint, idx: uint }
{ miner-id: uint, ustx: uint }
)
;; Maps miner address to uint miner-id
(define-map miners
{ miner: principal }
{ miner-id: uint }
)
;; Returns miner ID if it has been created
(define-read-only (get-miner-id (miner principal))
(get miner-id (map-get? miners { miner: miner }))
)
;; Returns miners ID if it has been created, or creates and returns new
(define-private (get-or-create-miner-id (miner principal))
(match (get miner-id (map-get? miners { miner: miner }))
value value
(let
((new-id (+ u1 (var-get miners-nonce))))
(map-set miners
{ miner: miner }
{ miner-id: new-id}
)
(var-set miners-nonce new-id)
new-id
)
)
)
;; TO DO: think about adding amount to mined-blocks map.
(define-map block-commit
{ stacks-block-height: uint }
{ amount: uint,
amount-to-stackers: uint,
amount-to-city: uint
}
)
(define-map miners-block-commitment
{ miner-id: uint, stacks-block-height: uint }
{ committed: bool }
)
;; How many uSTX are mined per reward cycle, and how many tokens are locked up in the same reward cycle.
(define-map tokens-per-cycle
{ reward-cycle: uint }
{ total-ustx: uint, total-tokens: uint }
)
;; Who has locked up how many tokens for a given reward cycle.
(define-map stacked-per-cycle
{ stacker: principal, reward-cycle: uint }
{ amount-token: uint }
)
;; The fungible token that can be Stacked.
(define-fungible-token resonancetoken u10000000)
(define-public (register-miner (memo (optional (buff 34))))
(let
(
(new-id (+ u1 (var-get miners-nonce)))
(threshold (var-get mining-activation-threshold))
)
(asserts! (is-none (map-get? miners { miner: tx-sender }))
(err ERR-MINER-ALREADY-REGISTERED))
(asserts! (<= new-id threshold)
(err ERR-MINING-ACTIVATION-THRESHOLD-REACHED))
(if (is-some memo)
(print memo)
none
)
(map-set miners
{ miner: tx-sender }
{ miner-id: new-id }
)
(var-set miners-nonce new-id)
(if (is-eq new-id threshold)
(let
(
(first-stacking-block-val (+ block-height MINING-ACTIVATION-DELAY))
)
(var-set mining-activation-threshold-reached true)
(var-set first-stacking-block first-stacking-block-val)
(var-set coinbase-threshold-1 (+ first-stacking-block-val MINING-HALVING-BLOCKS))
(var-set coinbase-threshold-2 (+ first-stacking-block-val (* u2 MINING-HALVING-BLOCKS)))
(var-set coinbase-threshold-3 (+ first-stacking-block-val (* u3 MINING-HALVING-BLOCKS)))
(var-set coinbase-threshold-4 (+ first-stacking-block-val (* u4 MINING-HALVING-BLOCKS)))
(var-set coinbase-threshold-5 (+ first-stacking-block-val (* u5 MINING-HALVING-BLOCKS)))
(ok true)
)
(ok true)
)
)
)
;; Getter for checking if mining is activated
(define-read-only (get-mining-activation-status)
(var-get mining-activation-threshold-reached)
)
;; Getter for current registration threshold
(define-read-only (get-registered-miners-threshold)
(var-get mining-activation-threshold)
)
(define-read-only (get-registered-miners-nonce)
(var-get miners-nonce)
)
;; Function for deciding how many tokens to mint, depending on when they were mined.
(define-read-only (get-coinbase-amount (miner-block-height uint))
(let
(
;; set a new variable to make things easier to read
(activation-block-height (var-get first-stacking-block))
)
;; determine if mining was active, return 0 if not
(asserts! (>= miner-block-height activation-block-height) u0)
;; evaluate current block height against issuance schedule and return correct coinbase amount
;; halvings occur every 210,000 blocks for 1,050,000 Stacks blocks
;; then mining continues indefinitely with 3,125 CityCoins as the reward
(asserts! (> miner-block-height (var-get coinbase-threshold-1))
(if (<= (- miner-block-height activation-block-height) u10000)
u250000 ;; bonus reward first 10,000 blocks
u100000 ;; standard reward remaining 200,000 blocks until 1st halving
)
)
(asserts! (> miner-block-height (var-get coinbase-threshold-2)) u50000) ;; between 1st and 2nd halving u50000
(asserts! (> miner-block-height (var-get coinbase-threshold-3)) u25000) ;; between 2nd and 3rd halving u25000
(asserts! (> miner-block-height (var-get coinbase-threshold-4)) u12500) ;; between 3rd and 4th halving u12500
(asserts! (> miner-block-height (var-get coinbase-threshold-5)) u6250) ;; between 4th and 5th halving u6250
;; default value after 5th halving
u3125
)
)
;; Getter for getting the list of miners and uSTX committments for a given block.
(define-read-only (get-miners-at-block (stacks-block-height uint))
(get miners (fold
get-miners-at-block-closure
(get-uint-list (get miners-count (get-mined-block-or-default stacks-block-height)))
{ stacks-block-height: stacks-block-height, miners: (list )}
))
)
(define-private (get-miners-at-block-closure (idx uint) (data { stacks-block-height: uint, miners: (list 128 { miner-id: uint, ustx: uint })}))
(match (map-get? blocks-miners { stacks-block-height: (get stacks-block-height data), idx: idx })
miner
{
stacks-block-height: (get stacks-block-height data),
miners: (unwrap-panic (as-max-len? (append (get miners data) miner) u128))
}
data
)
)
;; Getter for getting how many tokens are Stacked by the given principal in the given reward cycle.
(define-read-only (get-stacked-in-cycle (stacker principal) (reward-cycle uint))
(match (map-get? stacked-per-cycle { stacker: stacker, reward-cycle: reward-cycle })
stacked-rec (get amount-token stacked-rec)
u0
)
)
;; Getter for getting how many uSTX are committed and tokens are Stacked per reward cycle.
(define-read-only (get-tokens-per-cycle (rc uint))
(match (map-get? tokens-per-cycle { reward-cycle: rc })
token-info token-info
{ total-ustx: u0, total-tokens: u0 }
)
)
;; API endpoint for getting statistics about this PoX-lite contract.
;; Compare to /v2/pox on the Stacks node.
(define-read-only (get-pox-lite-info)
(match (get-reward-cycle block-height)
cur-reward-cycle
(ok
(let (
(token-info (get-tokens-per-cycle cur-reward-cycle))
(total-ft-supply (ft-get-supply citycoins))
(total-ustx-supply (stx-get-balance (as-contract tx-sender)))
)
{
reward-cycle-id: cur-reward-cycle,
first-block-height: (var-get first-stacking-block),
reward-cycle-length: (var-get reward-cycle-length),
total-supply: total-ft-supply,
total-ustx-locked: total-ustx-supply,
cur-liquid-supply: (- total-ft-supply (get total-tokens token-info)),
cur-locked-supply: (get total-tokens token-info),
cur-ustx-committed: (get total-ustx token-info)
})
)
(err ERR-STACKING-NOT-AVAILABLE)
)
)
;; Produce the new tokens for the given claimant, who won the tokens at the given Stacks block height.
(define-private (mint-coinbase (recipient principal) (stacks-block-ht uint))
(ft-mint? citycoins (get-coinbase-amount stacks-block-ht) recipient)
)
;; Getter to obtain the list of miners and uSTX commitments at a given Stacks block height,
;; OR, an empty such structure.
(define-private (get-mined-block-or-default (stacks-block-height uint))
(match (map-get? mined-blocks { stacks-block-height: stacks-block-height })
block block
{
miners-count: u0,
least-commitment-idx: u0,
least-commitment-ustx: u0,
claimed: false,
})
)
;; Given stacks-block-height, return how many uSTX were committed in total
(define-read-only (get-block-commit-total (stacks-block-height uint))
(default-to u0 (get amount (map-get? block-commit {stacks-block-height: stacks-block-height})))
)
;; Given stacks-block-height, return how many uSTX were committed to stackers
(define-read-only (get-block-commit-to-stackers (stacks-block-height uint))
(default-to u0 (get amount-to-stackers (map-get? block-commit {stacks-block-height: stacks-block-height})))
)
;; Given stacks-block-height, return how many uSTX were committed to the city
(define-read-only (get-block-commit-to-city (stacks-block-height uint))
(default-to u0 (get amount-to-city (map-get? block-commit {stacks-block-height: stacks-block-height})))
)
;; Inner fold function to determine which miner won the token batch at a particular Stacks block height, given a sampling value.
(define-private (get-block-winner-closure (idx uint) (data { stacks-block-height: uint, sample: uint, sum: uint, winner: (optional { miner-id: uint, ustx: uint})}))
(match (map-get? blocks-miners { stacks-block-height: (get stacks-block-height data), idx: idx})
miner
(let
(
(sum (get sum data))
(sample (get sample data))
(ustx (get ustx miner))
(next-sum (+ sum ustx))
(new-winner
(if (and (>= sample sum) (< sample next-sum))
(some miner)
(get winner data)
)
)
)
{
stacks-block-height: (get stacks-block-height data),
sample: sample,
sum: next-sum,
winner: new-winner
}
)
data
)
)
;; Determine who won a given batch of tokens, given a random sample and a list of miners and commitments.
;; The probability that a given miner wins the batch is proportional to how many uSTX it committed out of the
;; sum of commitments for this block.
(define-read-only (get-block-winner (stacks-block-height uint) (random-sample uint))
(let
(
(commit-total (get-block-commit-total stacks-block-height))
)
(if (> commit-total u0)
(get winner (fold
get-block-winner-closure
(get-uint-list (get miners-count (get-mined-block-or-default stacks-block-height)))
{
stacks-block-height: stacks-block-height,
sample: (mod random-sample commit-total),
sum: u0,
winner: none
}
))
none
)
)
)
;; Determine if a given miner has already mined at given block height
(define-read-only (has-mined (miner-id uint) (stacks-block-height uint))
(is-some (map-get? miners-block-commitment
{ miner-id: miner-id, stacks-block-height: stacks-block-height }
))
)
;; Determine whether or not the given principal can claim the mined tokens at a particular block height,
;; given the miners record for that block height, a random sample, and the current block height.
(define-read-only (can-claim-tokens (claimer principal)
(claimer-stacks-block-height uint)
(random-sample uint)
(block {
miners-count: uint,
least-commitment-idx: uint,
least-commitment-ustx: uint,
claimed: bool
})
(current-stacks-block uint))
(let (
(claimer-id (unwrap! (get-miner-id claimer) (err ERR-MINER-ID-NOT-FOUND)))
(reward-maturity (var-get token-reward-maturity))
(maximum-stacks-block-height
(if (>= current-stacks-block reward-maturity)
(- current-stacks-block reward-maturity)
u0))
)
(if (< claimer-stacks-block-height maximum-stacks-block-height)
(begin
(asserts! (not (get claimed block))
(err ERR-ALREADY-CLAIMED))
(match (get-block-winner claimer-stacks-block-height random-sample)
winner-rec (if (is-eq claimer-id (get miner-id winner-rec))
(ok true)
(err ERR-UNAUTHORIZED))
(err ERR-NO-WINNER))
)
(err ERR-IMMATURE-TOKEN-REWARD)))
)
;; Mark a batch of mined tokens as claimed, so no one else can go and claim them.
(define-private (set-tokens-claimed (claimed-stacks-block-height uint))
(let (
(miner-rec (unwrap!
(map-get? mined-blocks { stacks-block-height: claimed-stacks-block-height })
(err ERR-NO-WINNER)))
)
(begin
(asserts! (not (get claimed miner-rec))
(err ERR-ALREADY-CLAIMED))
(map-set mined-blocks
{ stacks-block-height: claimed-stacks-block-height }
(merge miner-rec { claimed: true })
)
(ok true)))
)
;; Determine whether or not the given miner can actually mine tokens right now.
;; * Stacking must be active for this smart contract
;; * No more than 31 miners must have mined already
;; * This miner hasn't mined in this block before
;; * The miner is committing a positive number of uSTX
;; * The miner has the uSTX to commit
(define-read-only (can-mine-tokens (miner principal) (miner-id uint) (stacks-block-height uint) (amount-ustx uint))
(let
(
(block (get-mined-block-or-default stacks-block-height))
)
(if (and (is-eq MAX-MINERS-COUNT (get miners-count block)) (<= amount-ustx (get least-commitment-ustx block)))
(err ERR-TOO-SMALL-COMMITMENT)
(begin
(asserts! (is-some (get-reward-cycle stacks-block-height))
(err ERR-STACKING-NOT-AVAILABLE))
(asserts! (not (has-mined miner-id stacks-block-height))
(err ERR-ALREADY-MINED))
(asserts! (> amount-ustx u0)
(err ERR-CANNOT-MINE))
(asserts! (>= (stx-get-balance miner) amount-ustx)
(err ERR-INSUFFICIENT-BALANCE))
(ok true)
)
)
)
)
;; Determine if a Stacker can Stack their tokens. Like PoX, they must supply
;; a future Stacks block height at which Stacking begins, as well as a lock-up period
;; in reward cycles.
;; * The Stacker's start block height must be in the future
;; * The first reward cycle must be _after_ the current reward cycle
;; * The lock period must be valid (positive, but no greater than the maximum allowed period)
;; * The Stacker must have tokens to Stack.
(define-read-only (can-stack-tokens (stacker principal) (amount-tokens uint) (now-stacks-ht uint) (start-stacks-ht uint) (lock-period uint))
(let (
(cur-reward-cycle (unwrap! (get-reward-cycle now-stacks-ht) (err ERR-STACKING-NOT-AVAILABLE)))
(start-reward-cycle (+ u1 (unwrap! (get-reward-cycle start-stacks-ht) (err ERR-STACKING-NOT-AVAILABLE))))
(max-lockup (var-get max-reward-cycles))
)
(begin
(asserts! (< now-stacks-ht start-stacks-ht)
(err ERR-CANNOT-STACK))
(asserts! (and (> lock-period u0) (<= lock-period max-lockup))
(err ERR-CANNOT-STACK))
(asserts! (> amount-tokens u0)
(err ERR-CANNOT-STACK))
(asserts! (<= amount-tokens (ft-get-balance citycoins stacker))
(err ERR-INSUFFICIENT-BALANCE))
(ok true)
))
)
;; Determine how many uSTX a Stacker is allowed to claim, given the reward cycle they Stacked in and the current block height.
;; This method only returns a positive value if:
;; * The current block height is in a subsequent reward cycle
;; * The Stacker actually did lock up some tokens in the target reward cycle
;; * The Stacker locked up _enough_ tokens to get at least one uSTX.
;; It's possible to Stack tokens but not receive uSTX. For example, no miners may have mined in this reward cycle.
;; As another example, you may have Stacked so few that you'd be entitled to less than 1 uSTX.
(define-read-only (get-entitled-stacking-reward (stacker principal) (target-reward-cycle uint) (cur-block-height uint))
(let (
(stacked-this-cycle
(get amount-token
(default-to { amount-token: u0 }
(map-get? stacked-per-cycle { stacker: stacker, reward-cycle: target-reward-cycle }))))
(total-tokens-this-cycle
(default-to { total-ustx: u0, total-tokens: u0 }
(map-get? tokens-per-cycle { reward-cycle: target-reward-cycle })))
)
(match (get-reward-cycle cur-block-height)
cur-reward-cycle
(if (or (<= cur-reward-cycle target-reward-cycle) (is-eq u0 (get total-tokens total-tokens-this-cycle)))
;; either this reward cycle hasn't finished yet, or the Stacker contributed nothing
u0
;; (total-ustx * this-stackers-tokens) / total-tokens-stacked
(/ (* (get total-ustx total-tokens-this-cycle) stacked-this-cycle)
(get total-tokens total-tokens-this-cycle))
)
;; before first reward cycle
u0
))
)
;; Helper variable used only to achieve "dynamic" filter condition in closure function called by `filter`
(define-data-var miner-to-kick (optional {miner-id: uint, amount-ustx: uint}) none)
;; Inner filter function.
;; Returns true if supplied miner in not miner who committed the least and needs to be kicked out of the list
(define-private (remove-miner-to-kick-closure (miner-data {miner-id: uint, amount-ustx: uint}))
(not
(is-eq miner-data (unwrap-panic (var-get miner-to-kick)))
)
)
(define-private (find-least (miner-data {miner-id: uint, amount-ustx: uint})
(ret-data (optional {miner-id: uint, amount-ustx: uint})))
(if (is-some ret-data)
(if ( < (get amount-ustx miner-data) (default-to u0 (get amount-ustx ret-data)))
(some miner-data)
ret-data
)
(some miner-data)
)
)
;; Mark a miner as having mined in a given Stacks block and committed the given uSTX.
(define-private (set-tokens-mined (miner principal) (miner-id uint) (stacks-block-height uint) (commit-ustx uint) (commit-ustx-to-stackers uint) (commit-ustx-to-city uint))
(let (
(block (get-mined-block-or-default stacks-block-height))
(increased-miners-count (+ (get miners-count block) u1))
(new-idx increased-miners-count)
(least-commitment-idx (get least-commitment-idx block))
(least-commitment-ustx (get least-commitment-ustx block))
(reward-cycle (unwrap! (get-reward-cycle stacks-block-height)
(err ERR-STACKING-NOT-AVAILABLE)))
(tokens-mined (default-to { total-ustx: u0, total-tokens: u0 }
(map-get? tokens-per-cycle { reward-cycle: reward-cycle }))
)
)
(begin
(if (> MAX-MINERS-COUNT (get miners-count block))
(begin
;; list is not full - add new miner and calculate if he committed the least
(map-set blocks-miners
{ stacks-block-height: stacks-block-height, idx: new-idx }
{ miner-id: miner-id, ustx: commit-ustx }
)
(map-set mined-blocks
{ stacks-block-height: stacks-block-height }
{
miners-count: increased-miners-count,
least-commitment-idx: (if (or (is-eq new-idx u1) (< commit-ustx least-commitment-ustx)) new-idx least-commitment-idx),
least-commitment-ustx: (if (or (is-eq new-idx u1) (< commit-ustx least-commitment-ustx)) commit-ustx least-commitment-ustx),
claimed: false
}
)
)
(begin
;; list is full - replace miner who committed the least with new one and calculate new miner who committed the least
(map-set blocks-miners
{ stacks-block-height: stacks-block-height, idx: least-commitment-idx }
{ miner-id: miner-id, ustx: commit-ustx }
)
(let
(
(least-commitment (find-least-commitment stacks-block-height))
)
(map-set mined-blocks
{ stacks-block-height: stacks-block-height }
{
miners-count: MAX-MINERS-COUNT,
least-commitment-idx: (get least-commitment-idx least-commitment),
least-commitment-ustx: (get least-commitment-ustx least-commitment),
claimed: false
}
)
)
)
)
(map-set miners-block-commitment
{ miner-id: miner-id, stacks-block-height: stacks-block-height}
{ committed: true }
)
(map-set tokens-per-cycle
{ reward-cycle: reward-cycle }
{ total-ustx: (+ commit-ustx-to-stackers (get total-ustx tokens-mined)), total-tokens: (get total-tokens tokens-mined) }
)
(map-set block-commit
{ stacks-block-height: stacks-block-height }
{
amount: (+ commit-ustx (get-block-commit-total stacks-block-height)),
amount-to-stackers: (+ commit-ustx-to-stackers (get-block-commit-to-stackers stacks-block-height)),
amount-to-city: (+ commit-ustx-to-city (get-block-commit-to-city stacks-block-height))
}
)
(ok true)
))
)
(define-read-only (find-least-commitment (stacks-block-height uint))
(fold find-least-commitment-closure LONG-UINT-LIST { stacks-block-height: stacks-block-height, least-commitment-idx: u0, least-commitment-ustx: u0 })
)
(define-private (find-least-commitment-closure (idx uint) (data { stacks-block-height: uint, least-commitment-idx: uint, least-commitment-ustx: uint }))
(match (get ustx (map-get? blocks-miners { stacks-block-height: (get stacks-block-height data), idx: idx }))
ustx
(if (or (is-eq idx u1) (< ustx (get least-commitment-ustx data)))
{
stacks-block-height: (get stacks-block-height data),
least-commitment-idx: (if (> ustx u0) idx u0), ;; if is used here to return 0 when called on block without miners
least-commitment-ustx: ustx
}
data
)
data
)
)
;; Get the reward cycle for a given Stacks block height
(define-read-only (get-reward-cycle (stacks-bh uint))
(let (
(first-stack-block (var-get first-stacking-block))
(rc-len (var-get reward-cycle-length))
)
(if (>= stacks-bh first-stack-block)
(some (/ (- stacks-bh first-stack-block) rc-len))
none
))
)
;; Get the first Stacks block height for a given reward cycle.
(define-read-only (get-first-block-height-in-reward-cycle (reward-cycle uint))
(+ (var-get first-stacking-block) (* (var-get reward-cycle-length) reward-cycle)))
;; Read the on-chain VRF and turn the lower 16 bytes into a uint, in order to sample the set of miners and determine
;; which one may claim the token batch for the given block height.
(define-read-only (get-random-uint-at-block (stacks-block uint))
(let (
(vrf-lower-uint-opt
(match (get-block-info? vrf-seed stacks-block)
vrf-seed (some (buff-to-uint-le (lower-16-le vrf-seed)))
none))
)
vrf-lower-uint-opt)
)
;; Inner fold function for Stacking tokens. Populates the stacked-per-cycle and tokens-per-cycle tables for each
;; reward cycle the Stacker is Stacking in.
(define-private (stack-tokens-closure (reward-cycle-idx uint) (commitment { stacker: principal, amt: uint, first: uint, last: uint }))
(let (
(stacker (get stacker commitment))
(amount-token (get amt commitment))
(first-reward-cycle (get first commitment))
(last-reward-cycle (get last commitment))
(target-reward-cycle (+ first-reward-cycle reward-cycle-idx))
(stacked-already (match (map-get? stacked-per-cycle { stacker: stacker, reward-cycle: target-reward-cycle })
rec (get amount-token rec)
u0))
(tokens-this-cycle (match (map-get? tokens-per-cycle { reward-cycle: target-reward-cycle })
rec rec
{ total-ustx: u0, total-tokens: u0 }))
)
(begin
(if (and (>= target-reward-cycle first-reward-cycle) (< target-reward-cycle last-reward-cycle))
(begin
(map-set stacked-per-cycle
{ stacker: stacker, reward-cycle: target-reward-cycle }
{ amount-token: (+ amount-token stacked-already) })
(map-set tokens-per-cycle
{ reward-cycle: target-reward-cycle }
{ total-ustx: (get total-ustx tokens-this-cycle), total-tokens: (+ amount-token (get total-tokens tokens-this-cycle)) })
true)
false)
{ stacker: stacker, amt: amount-token, first: first-reward-cycle, last: last-reward-cycle }
))
)
;; Stack the contract's tokens. Stacking will begin at the next reward cycle following
;; the reward cycle in which start-stacks-ht resides.
;; This method takes possession of the Stacker's tokens until the given number of reward cycles
;; has passed.
(define-public (stack-tokens (amount-tokens uint) (start-stacks-ht uint) (lock-period uint))
(let (
(start-reward-cycle (+ u1 (unwrap! (get-reward-cycle start-stacks-ht) (err ERR-STACKING-NOT-AVAILABLE))))
)
(begin
(try! (can-stack-tokens tx-sender amount-tokens block-height start-stacks-ht lock-period))
(unwrap! (ft-transfer? citycoins amount-tokens tx-sender (as-contract tx-sender))
(err ERR-INSUFFICIENT-BALANCE))
(fold stack-tokens-closure REWARD-CYCLE-INDEXES
{ stacker: tx-sender, amt: amount-tokens, first: start-reward-cycle, last: (+ start-reward-cycle lock-period) })
(ok true)
))
)
;; Mine tokens. The miner commits uSTX into this contract (which Stackers can claim later with claim-stacking-reward),
;; and in doing so, enters their candidacy to be able to claim the block reward (via claim-token-reward). The miner must
;; wait for a token maturity window in order to obtain the tokens. Once that window passes, they can get the tokens.
;; This ensures that no one knows the VRF seed that will be used to pick the winner.
(define-public (mine-tokens (amount-ustx uint) (memo (optional (buff 34))))
(begin
(if (is-some memo)
(print memo)
none
)
(mine-tokens-at-block block-height (get-or-create-miner-id tx-sender) amount-ustx)
)
)
(define-public (mine-tokens-over-5-blocks (amount-ustx uint))
(let
((miner-id (get-or-create-miner-id tx-sender)))
(asserts! (>= (stx-get-balance tx-sender) (* u5 amount-ustx))
(err ERR-INSUFFICIENT-BALANCE))
(try! (mine-tokens-at-block block-height miner-id amount-ustx))
(try! (mine-tokens-at-block (+ block-height u1) miner-id amount-ustx))
(try! (mine-tokens-at-block (+ block-height u2) miner-id amount-ustx))
(try! (mine-tokens-at-block (+ block-height u3) miner-id amount-ustx))
(try! (mine-tokens-at-block (+ block-height u4) miner-id amount-ustx))
(ok true)
)
)
(define-private (mine-tokens-at-block (stacks-block-height uint) (miner-id uint) (amount-ustx uint))
(let (
(rc (unwrap! (get-reward-cycle stacks-block-height)
(err ERR-STACKING-NOT-AVAILABLE)))
(total-stacked (get total-tokens (map-get? tokens-per-cycle { reward-cycle: rc })))
(total-stacked-ustx (default-to u0 total-stacked))
(stacked-something (not (is-eq total-stacked-ustx u0)))
(amount-ustx-to-stacker
(if stacked-something
(/ (* SPLIT_STACKER_PERCENTAGE amount-ustx) u100)
u0
)
)
(amount-ustx-to-city
(if stacked-something
(/ (* SPLIT_CITY_PERCENTAGE amount-ustx) u100)
amount-ustx
)
)
)
(begin
(try! (can-mine-tokens tx-sender miner-id stacks-block-height amount-ustx))
(try! (set-tokens-mined tx-sender miner-id stacks-block-height amount-ustx amount-ustx-to-stacker amount-ustx-to-city))
;; check if stacking is active
(if stacked-something
;; transfer with split if active
(begin
(unwrap-panic (stx-transfer? amount-ustx-to-stacker tx-sender (as-contract tx-sender)))
(unwrap-panic (stx-transfer? amount-ustx-to-city tx-sender (var-get city-wallet)))
)
;; transfer to custodied wallet if not active
(unwrap-panic (stx-transfer? amount-ustx-to-city tx-sender (var-get city-wallet)))
)
(ok true)
))
)
;; Claim the block reward. This mints and transfers out a miner's tokens if it is indeed the block winner for
;; the given Stacks block. The VRF seed will be sampled at the target mined stacks block height _plus_ the
;; maturity window, and if the miner (i.e. the caller of this function) both mined in the target Stacks block
;; and was later selected by the VRF as the winner, they will receive that block's token batch.
;; Note that this method actually mints the contract's tokens -- they do not exist until the miner calls
;; this method.
(define-public (claim-token-reward (mined-stacks-block-ht uint))
(let (
(random-sample (unwrap! (get-random-uint-at-block (+ mined-stacks-block-ht (var-get token-reward-maturity)))
(err ERR-IMMATURE-TOKEN-REWARD)))
(block (unwrap! (map-get? mined-blocks { stacks-block-height: mined-stacks-block-ht })
(err ERR-NO-WINNER)))
)
(begin
(try! (can-claim-tokens tx-sender mined-stacks-block-ht random-sample block block-height))
(try! (set-tokens-claimed mined-stacks-block-ht))
(unwrap-panic (mint-coinbase tx-sender mined-stacks-block-ht))
(ok true)
))
)
;; Claim a Stacking reward. Once a reward cycle passes, a Stacker can call this method to obtain any
;; uSTX that were committed to the contract during that reward cycle (proportional to how many tokens
;; they locked up).
(define-public (claim-stacking-reward (target-reward-cycle uint))
(let (
(stacker tx-sender)
(entitled-ustx (get-entitled-stacking-reward tx-sender target-reward-cycle block-height))
(stacked-in-cycle (get-stacked-in-cycle tx-sender target-reward-cycle))
)
(begin
(asserts! (> entitled-ustx u0)
(err ERR-NOTHING-TO-REDEEM))
;; can't claim again
(map-set stacked-per-cycle
{ stacker: tx-sender, reward-cycle: target-reward-cycle }
{ amount-token: u0 })
(try! (as-contract (stx-transfer? entitled-ustx tx-sender stacker)))
(try! (as-contract (ft-transfer? citycoins stacked-in-cycle tx-sender stacker)))
(ok true)
))
)
(define-read-only (get-total-supply-ustx)
(ok (stx-get-balance (as-contract tx-sender)))
)
(define-read-only (get-city-wallet)
(var-get city-wallet)
)
;; Update the city-wallet variable
;; This can only be called by the city-wallet principal.
;; Calling `set-city-wallet` from an outside contract (that is not the city-wallet principal)
;; is not allowed
(define-public (set-city-wallet (wallet-address principal))
(begin
(asserts! (is-eq contract-caller (var-get city-wallet)) (err ERR-UNAUTHORIZED))
(ok (var-set city-wallet wallet-address))
)
)
;;;;;;;;;;;;;;;;;;;;; SIP 010 ;;;;;;;;;;;;;;;;;;;;;;
;; testnet: (impl-trait 'STR8P3RD1EHA8AA37ERSSSZSWKS9T2GYQFGXNA4C.sip-010-trait-ft-standard.sip-010-trait)
(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait)
(define-public (transfer (amount uint) (from principal) (to principal) (memo (optional (buff 34))))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(if (is-some memo)
(print memo)
none
)
(ft-transfer? citycoins amount from to)
)
)
(define-read-only (get-name)
(ok "citycoins"))
(define-read-only (get-symbol)
(ok "CYCN"))
(define-read-only (get-decimals)
(ok u0))
(define-read-only (get-balance (user principal))
(ok (ft-get-balance citycoins user)))
(define-read-only (get-total-supply)
(ok (ft-get-supply citycoins)))
(define-read-only (get-token-uri)
(ok (var-get token-uri))) | 0x5dd3a45f50ac0071da180278c1b3b5e9637759bc62df736a12e594895f1c7ae3 | 19,193 | abort_by_response |
dmt-dao | ;; error codes
(define-constant ERR-NO-WINNER u0)
(define-constant ERR-NO-SUCH-MINER u1)
(define-constant ERR-IMMATURE-TOKEN-REWARD u2)
(define-constant ERR-UNAUTHORIZED u3)
(define-constant ERR-ALREADY-CLAIMED u4)
(define-constant ERR-STACKING-NOT-AVAILABLE u5)
(define-constant ERR-CANNOT-STACK u6)
(define-constant ERR-INSUFFICIENT-BALANCE u7)
(define-constant ERR-ALREADY-MINED u8)
(define-constant ERR-ROUND-FULL u9) ;; deprecated - this error is not used anymore
(define-constant ERR-NOTHING-TO-REDEEM u10)
(define-constant ERR-CANNOT-MINE u11)
(define-constant ERR-MINER-ALREADY-REGISTERED u12)
(define-constant ERR-MINING-ACTIVATION-THRESHOLD-REACHED u13)
(define-constant ERR-MINER-ID-NOT-FOUND u14)
(define-constant ERR-TOO-SMALL-COMMITMENT u15)
(define-constant ERR-TOO-MANY-MINERS u16)
(define-constant LONG-UINT-LIST (list
u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15 u16
u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31 u32
u33 u34 u35 u36 u37 u38 u39 u40 u41 u42 u43 u44 u45 u46 u47 u48
u49 u50 u51 u52 u53 u54 u55 u56 u57 u58 u59 u60 u61 u62 u63 u64
u65 u66 u67 u68 u69 u70 u71 u72 u73 u74 u75 u76 u77 u78 u79 u80
u81 u82 u83 u84 u85 u86 u87 u88 u89 u90 u91 u92 u93 u94 u95 u96
u97 u98 u99 u100 u101 u102 u103 u104 u105 u106 u107 u108 u109 u110 u111 u112
u113 u114 u115 u116 u117 u118 u119 u120 u121 u122 u123 u124 u125 u126 u127 u128
))
(define-constant TOKEN-REWARD-MATURITY u5) ;; how long a miner must wait before claiming their minted tokens
(define-constant ACTIVATION-HEIGHT u3000) ;; The beginning height of the mining process
(define-constant MAX-MINERS-COUNT u128) ;; maximum players in one cycle
(define-constant RTX_CUSTODIED_WALLET 'STKBS86JFA8BBJ1FF66QQEV855SQS6PWQ4TZ0ASQ) ;; the custodied wallet address for the city
(define-data-var dmt-wallet principal RTX_CUSTODIED_WALLET) ;; variable used in place of constant for easier testing
(define-data-var token-reward-maturity uint TOKEN-REWARD-MATURITY)
(define-data-var block-reward uint u10)
(define-data-var miners-nonce uint u0) ;; variable used to generate unique miner-id's
(define-data-var latest-cycle-height uint u0) ;; variable used to record latest cycle height. For example the latest block is 2008, then the latest-cycle-height is 2010
;; it will always be multiple of five
;; Bind Stacks block height to a list of up to 128 miners (and how much they mined) per block,
;; and track whether or not the miner has come back to claim their tokens and who mined the least.
(define-map mined-blocks
{ stacks-block-height: uint }
{
miners-count: uint,
commitment-ustx: uint,
winner-id: uint,
claimed: bool,
}
)
(define-map blocks-miners
{ stacks-block-height: uint, idx: uint }
{ miner-id: uint, ustx: uint }
)
;; Maps miner address to uint miner-id
(define-map miners
{ miner: principal }
{ miner-id: uint }
)
(define-map miners-block-commitment
{ miner-id: uint, stacks-block-height: uint }
{ committed: bool }
)
(define-read-only (get-mined-blocks (stacks-block-height uint))
;;(is-some (map-get? mined-blocks
;; { stacks-block-height: stacks-block-height }
;;))
(get-mined-block-or-default stacks-block-height)
)
(define-read-only (get-blocks-miners (stacks-block-height uint) (idx uint))
(match (map-get? blocks-miners
{ stacks-block-height: stacks-block-height, idx: idx }
)
miner miner
{
miner-id: u0,
ustx: u0,
}
)
)
;; Determine if a given miner has already mined at given block height
(define-read-only (has-mined (miner-id uint) (stacks-block-height uint))
(is-some (map-get? miners-block-commitment
{ miner-id: miner-id, stacks-block-height: stacks-block-height }
))
)
;; Returns miners ID if it has been created, or creates and returns new
(define-private (get-or-create-miner-id (miner principal))
(match (get miner-id (map-get? miners { miner: miner }))
value value
(let
((new-id (+ u1 (var-get miners-nonce))))
(map-set miners
{ miner: miner }
{ miner-id: new-id}
)
(var-set miners-nonce new-id)
new-id
)
)
)
(define-read-only (get-next-block-height)
(+ (- block-height (mod block-height u5)) u6)
)
;; Mine tokens. The miner commits uSTX into this contract (which Stackers can claim later with claim-stacking-reward),
;; and in doing so, enters their candidacy to be able to claim the block reward (via claim-token-reward). The miner must
;; wait for a token maturity window in order to obtain the tokens. Once that window passes, they can get the tokens.
;; This ensures that no one knows the VRF seed that will be used to pick the winner.
(define-public (mine-tokens (amount-ustx uint) (memo (optional (string-ascii 34))))
(begin
(let
(
(next-block-height (get-next-block-height))
)
(if (is-some memo)
(print memo)
none
)
(try! (mine-tokens-at-block next-block-height (get-or-create-miner-id tx-sender) (/ amount-ustx u5)))
(try! (mine-tokens-at-block (+ next-block-height u1) (get-or-create-miner-id tx-sender) (/ amount-ustx u5)))
(try! (mine-tokens-at-block (+ next-block-height u2) (get-or-create-miner-id tx-sender) (/ amount-ustx u5)))
(try! (mine-tokens-at-block (+ next-block-height u3) (get-or-create-miner-id tx-sender) (/ amount-ustx u5)))
(try! (mine-tokens-at-block (+ next-block-height u4) (get-or-create-miner-id tx-sender) (/ amount-ustx u5)))
)
(ok true)
)
)
(define-private (mine-tokens-at-block (stacks-block-height uint) (miner-id uint) (amount-ustx uint))
(begin
(try! (can-mine-tokens tx-sender miner-id stacks-block-height amount-ustx))
(try! (set-tokens-mined tx-sender miner-id stacks-block-height amount-ustx))
(unwrap-panic (stx-transfer? amount-ustx tx-sender (var-get dmt-wallet)))
(ok true)
)
)
;; Determine whether or not the given miner can actually mine tokens right now.
;; * This miner hasn't mined this cycle before
;; * The miner is committing a positive number of uSTX
;; * The miner has the uSTX to commit
(define-read-only (can-mine-tokens (miner principal) (miner-id uint) (stacks-block-height uint) (amount-ustx uint))
(let
(
(block (get-mined-block-or-default stacks-block-height))
)
(if (is-eq MAX-MINERS-COUNT (get miners-count block))
(err ERR-TOO-SMALL-COMMITMENT)
(begin
(asserts! (not (has-mined miner-id stacks-block-height))
(err ERR-ALREADY-MINED))
(asserts! (> amount-ustx u0)
(err ERR-CANNOT-MINE))
(asserts! (>= (stx-get-balance miner) amount-ustx)
(err ERR-INSUFFICIENT-BALANCE))
(ok true)
)
)
)
)
;; Getter to obtain the list of miners and uSTX commitments at a given Stacks block height,
;; OR, an empty such structure.
(define-private (get-mined-block-or-default (stacks-block-height uint))
(match (map-get? mined-blocks { stacks-block-height: stacks-block-height })
block block
{
miners-count: u0,
commitment-ustx: u0,
winner-id: u0,
claimed: false,
})
)
;; Mark a miner as having mined in a given Stacks block and committed the given uSTX.
(define-private (set-tokens-mined (miner principal) (miner-id uint) (stacks-block-height uint) (commit-ustx uint))
(let (
(block (get-mined-block-or-default stacks-block-height))
(increased-miners-count (+ (get miners-count block) u1))
(new-idx increased-miners-count)
(commitment-ustx (get commitment-ustx block))
)
(begin
(begin
;; list is not full - add new miner and calculate if he committed the least
(map-set blocks-miners
{ stacks-block-height: stacks-block-height, idx: new-idx }
{ miner-id: miner-id, ustx: commit-ustx }
)
(map-set miners-ids
{ miner-id: miner-id }
{ miner-addr: tx-sender }
)
(map-set mined-blocks
{ stacks-block-height: stacks-block-height }
{
miners-count: increased-miners-count,
commitment-ustx: (+ commitment-ustx commit-ustx),
winner-id: u0,
claimed: false
}
)
)
;;TODO
(map-set miners-block-commitment
{ miner-id: miner-id, stacks-block-height: stacks-block-height}
{ committed: true }
)
(if (> MAX-MINERS-COUNT (get miners-count block))
(ok true)
(err ERR-TOO-MANY-MINERS)
)
))
)
(define-fungible-token resonancetoken u10000000)
(define-public (claim-token-reward (mined-stacks-block-ht uint))
(let (
(random-sample (unwrap! (get-random-uint-at-block (+ mined-stacks-block-ht (var-get token-reward-maturity)))
(err ERR-IMMATURE-TOKEN-REWARD)))
(block (unwrap! (map-get? mined-blocks { stacks-block-height: mined-stacks-block-ht })
(err ERR-NO-WINNER)))
)
(begin
(try! (can-claim-tokens tx-sender mined-stacks-block-ht random-sample block-height))
(try! (set-tokens-claimed mined-stacks-block-ht))
(unwrap-panic (mint-coinbase tx-sender mined-stacks-block-ht))
(ok true)
))
)
;; Returns miner ID if it has been created
(define-read-only (get-miner-id (miner principal))
(get miner-id (map-get? miners { miner: miner }))
)
;; Mark a batch of mined tokens as claimed, so no one else can go and claim them.
(define-private (set-tokens-claimed (claimed-stacks-block-height uint))
(let (
(miner-rec (unwrap!
(map-get? mined-blocks { stacks-block-height: claimed-stacks-block-height })
(err ERR-NO-WINNER)))
)
(begin
(asserts! (not (get claimed miner-rec))
(err ERR-ALREADY-CLAIMED))
(map-set mined-blocks
{ stacks-block-height: claimed-stacks-block-height }
(merge miner-rec { claimed: true })
)
(ok true)))
)
(define-read-only (can-claim-tokens (claimer principal)
(claimer-stacks-block-height uint)
(random-sample uint)
(current-stacks-block uint))
(let (
(block (unwrap! (map-get? mined-blocks { stacks-block-height: claimer-stacks-block-height })
(err ERR-NO-WINNER)))
(claimer-id (unwrap! (get-miner-id claimer)
(err ERR-MINER-ID-NOT-FOUND)))
(reward-maturity (var-get token-reward-maturity))
)
(if (< claimer-stacks-block-height (- current-stacks-block (var-get token-reward-maturity)))
(begin
(asserts! (not (get claimed block))
(err ERR-ALREADY-CLAIMED))
(match (get-block-winner claimer-stacks-block-height random-sample)
winner-rec (if (is-eq claimer-id (get miner-id winner-rec))
(ok true)
(err ERR-UNAUTHORIZED))
(err ERR-NO-WINNER))
)
(err ERR-IMMATURE-TOKEN-REWARD)))
)
;; Determine who won a given batch of tokens, given a random sample and a list of miners and commitments.
;; The probability that a given miner wins the batch is proportional to how many uSTX it committed out of the
;; sum of commitments for this block.
(define-read-only (get-block-winner (stacks-block-height uint) (random-sample uint))
(let
(
(commit-total (default-to u0 (get commitment-ustx (map-get? mined-blocks {stacks-block-height: stacks-block-height}))))
)
(if (> commit-total u0)
(get winner (fold
get-block-winner-closure
(get-uint-list (get miners-count (get-mined-block-or-default stacks-block-height)))
{
stacks-block-height: stacks-block-height,
sample: (mod random-sample commit-total),
sum: u0,
winner: none
}
))
none
)
)
)
;; Inner fold function to determine which miner won the token batch at a particular Stacks block height, given a sampling value.
(define-private (get-block-winner-closure (idx uint) (data { stacks-block-height: uint, sample: uint, sum: uint, winner: (optional { miner-id: uint, ustx: uint})}))
(begin
(match (map-get? blocks-miners { stacks-block-height: (get stacks-block-height data), idx: idx})
miner
(let
(
(sum (get sum data))
(sample (get sample data))
(ustx (get ustx miner))
(next-sum (+ sum ustx))
(new-winner
(if (and (>= sample sum) (< sample next-sum))
(some miner)
(get winner data)
)
)
)
{
stacks-block-height: (get stacks-block-height data),
sample: sample,
sum: next-sum,
winner: new-winner
}
)
data
)
)
)
(define-map UintLists
uint ;; size
(list 128 uint) ;; actual list
)
(define-map miners-ids
{miner-id: uint}
{miner-addr: principal}
)
(define-read-only (get-miner-addr (miner-id uint))
(match (map-get? miners-ids { miner-id: miner-id })
miner miner
{
miner-addr: 'STWNR9453W215A1HGRN4GPXE2SDHW2S51WFTCTEE
})
)
(define-private (get-uint-list (size uint))
(default-to (list ) (map-get? UintLists size))
)
(fold fill-uint-list-closure LONG-UINT-LIST true)
(define-private (fill-uint-list-closure (idx uint) (x bool))
(if (is-eq idx u1)
(map-insert UintLists
idx
(unwrap-panic (as-max-len? (list u1) u128))
)
(map-insert UintLists
idx
(unwrap-panic (as-max-len? (append (unwrap-panic (map-get? UintLists (- idx u1))) idx) u128))
)
)
)
;; Read the on-chain VRF and turn the lower 16 bytes into a uint, in order to sample the set of miners and determine
;; which one may claim the token batch for the given block height.
(define-read-only (get-random-uint-at-block (stacks-block uint))
(let
(
(vrf-lower-uint-opt
(match (get-block-info? vrf-seed stacks-block)
vrf-seed (some (buff-to-uint-le (lower-16-le vrf-seed)))
none)
)
)
vrf-lower-uint-opt
)
)
;; lookup table for converting 1-byte buffers to uints via index-of
(define-constant BUFF-TO-BYTE (list
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f
0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f
0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f
0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a 0x3b 0x3c 0x3d 0x3e 0x3f
0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f
0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f
0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e 0x6f
0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b 0x7c 0x7d 0x7e 0x7f
0x80 0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f
0x90 0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f
0xa0 0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf
0xb0 0xb1 0xb2 0xb3 0xb4 0xb5 0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf
0xc0 0xc1 0xc2 0xc3 0xc4 0xc5 0xc6 0xc7 0xc8 0xc9 0xca 0xcb 0xcc 0xcd 0xce 0xcf
0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf
0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef
0xf0 0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff
))
;; Inner closure for obtaining the lower 16 bytes of a 32-byte buff
(define-private (lower-16-le-closure (idx uint) (input { acc: (buff 16), data: (buff 32) }))
(let (
(acc (get acc input))
(data (get data input))
(byte (unwrap-panic (element-at data idx)))
)
{
acc: (unwrap-panic (as-max-len? (concat acc byte) u16)),
data: data
})
)
;; Convert the lower 16 bytes of a buff into a little-endian uint.
(define-private (lower-16-le (input (buff 32)))
(get acc
(fold lower-16-le-closure (list u16 u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31) { acc: 0x, data: input })
)
)
;; Convert a 1-byte buffer into its uint representation.
(define-private (buff-to-u8 (byte (buff 1)))
(unwrap-panic (index-of BUFF-TO-BYTE byte)))
;; Inner fold function for converting a 16-byte buff into a uint.
(define-private (add-and-shift-uint-le (idx uint) (input { acc: uint, data: (buff 16) }))
(let (
(acc (get acc input))
(data (get data input))
(byte (buff-to-u8 (unwrap-panic (element-at data idx))))
)
{
;; acc = byte * (2**(8 * (15 - idx))) + acc
acc: (+ (* byte (pow u2 (* u8 (- u15 idx)))) acc),
data: data
})
)
;; Convert a little-endian 16-byte buff into a uint.
(define-private (buff-to-uint-le (word (buff 16)))
(get acc
(fold add-and-shift-uint-le (list u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15) { acc: u0, data: word })
)
)
(define-private (mint-coinbase (recipient principal) (stacks-block-ht uint))
(ft-mint? resonancetoken (var-get block-reward) recipient)
)
;; define initial token URI
(define-data-var token-uri (optional (string-utf8 256)) (some u"<link to token-uri>"))
;;;;;;;;;;;;;;;;;;;;; SIP 010 ;;;;;;;;;;;;;;;;;;;;;;
;; testnet
;; (impl-trait 'ST2EKQHV1XVFET0FP9VC4EBTFSCA1GVACD6QR3RXR.sip-010-trait-ft-standard.sip-010-trait)
;; mainnet
;;(impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait)
(define-read-only (get-name)
(ok "Resonance Token"))
(define-public (transfer (amount uint) (from principal) (to principal) (memo (optional (buff 34))))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(if (is-some memo)
(print memo)
none
)
(ft-transfer? resonancetoken amount from to)
)
)
(define-read-only (get-symbol)
(ok "RTX"))
;; minimal unit is 0
(define-read-only (get-decimals)
(ok u0))
(define-read-only (get-balance (user principal))
(ok (ft-get-balance resonancetoken user)))
(define-read-only (get-total-supply)
(ok (ft-get-supply resonancetoken)))
(define-read-only (get-token-uri)
(ok (var-get token-uri))) | 0x88461aa9445df11e35e23cf4883e42e47490c9d2a1a493bac4897916adb4f0cb | 19,259 | success |
sip-010 | ;; sip-010 trait
;; use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
(define-trait ft-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance-of (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
)
| 0xc0c1b03c634e94565122795b6d78293f57bcfd0a63b329eb11f382ceb1d32e91 | 19,908 | success |
token-sangwon |
;; sws-token-01
;; we implement the sip-010
;; In mainnet use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
;; for testnet
(impl-trait 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA.sip-010.ft-trait)
;; (impl-trait sip-10-ft-standard.ft-trait)
;; constants
;;
(define-fungible-token sangwon-token)
(define-constant contract-owner 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA)
(define-constant not-owner-err (err u63))
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance sangwon-token owner))
)
;; returns the total number of tokens
(define-read-only (get-total-supply)
(ok (ft-get-supply sangwon-token))
)
;; returns the token name
(define-read-only (get-name)
(ok "Sangwon Token")
)
(define-read-only (get-symbol)
(ok "SWS")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u3) ;; because we can, and interesting for testing wallets and other clients
)
(define-read-only (get-token-uri)
(ok (some u"empty"))
)
;; data maps and vars
;;
;; private functions
;;
(define-public (owner-mint (account principal) (amount uint))
(if (<= amount u0)
(err u0)
(begin
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(ft-mint? sangwon-token amount account)
)
)
)
;; public functions
;;
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (>= (ft-get-balance sangwon-token sender) amount)
(begin
(print "sangwon.transfer")
(print amount)
(print tx-sender)
(print recipient)
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(print (ft-transfer? sangwon-token amount sender recipient))
)
(err u0)
)
)
;; (contract-call? .sws-token-01 get-name)
;; (contract-call? .sws-token-01 owner-mint 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA u10)
;; (contract-call? .sws-token-01 get-balance-of 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA) | 0x727ed2a2ee5ae6c1e4d3867893404369b31135d7d70bbd523c784139c92dce57 | 19,910 | abort_by_response |
token-sangwon |
;; sws-token-01
;; we implement the sip-010
;; In mainnet use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
;; for testnet
(impl-trait 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA.sip-010.ft-trait)
;; (impl-trait sip-10-ft-standard.ft-trait)
;; constants
;;
(define-fungible-token sangwon-token)
(define-constant contract-owner 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA)
(define-constant not-owner-err (err u63))
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance sangwon-token owner))
)
;; returns the total number of tokens
(define-read-only (get-total-supply)
(ok (ft-get-supply sangwon-token))
)
;; returns the token name
(define-read-only (get-name)
(ok "Sangwon Token")
)
(define-read-only (get-symbol)
(ok "SWS")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u3) ;; because we can, and interesting for testing wallets and other clients
)
(define-read-only (get-token-uri)
(ok (some u"empty"))
)
;; data maps and vars
;;
;; private functions
;;
(define-public (owner-mint (account principal) (amount uint))
(if (<= amount u0)
(err u0)
(begin
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(ft-mint? sangwon-token amount account)
)
)
)
;; public functions
;;
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (>= (ft-get-balance sangwon-token sender) amount)
(begin
(print "sangwon.transfer")
(print amount)
(print tx-sender)
(print recipient)
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(print (ft-transfer? sangwon-token amount sender recipient))
)
(err u0)
)
)
;; (contract-call? .sws-token-01 get-name)
;; (contract-call? .sws-token-01 owner-mint 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA u10)
;; (contract-call? .sws-token-01 get-balance-of 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA) | 0x727ed2a2ee5ae6c1e4d3867893404369b31135d7d70bbd523c784139c92dce57 | 19,911 | abort_by_response |
sangwon-token |
;; sws-token-01
;; we implement the sip-010
;; In mainnet use https://explorer.stacks.co/txid/SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-10-ft-standard
;; for testnet
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010.ft-trait)
;; (impl-trait sip-10-ft-standard.ft-trait)
;; constants
;;
(define-fungible-token sangwon-token)
(define-constant contract-owner 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF)
(define-constant not-owner-err (err u63))
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance sangwon-token owner))
)
;; returns the total number of tokens
(define-read-only (get-total-supply)
(ok (ft-get-supply sangwon-token))
)
;; returns the token name
(define-read-only (get-name)
(ok "Sangwon Token")
)
(define-read-only (get-symbol)
(ok "SWS")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u3) ;; because we can, and interesting for testing wallets and other clients
)
(define-read-only (get-token-uri)
(ok (some u"empty"))
)
;; data maps and vars
;;
;; private functions
;;
(define-public (owner-mint (account principal) (amount uint))
(if (<= amount u0)
(err u0)
(begin
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(ft-mint? sangwon-token amount account)
)
)
)
;; public functions
;;
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (>= (ft-get-balance sangwon-token sender) amount)
(begin
(print "sangwon.transfer")
(print amount)
(print tx-sender)
(print recipient)
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(print (ft-transfer? sangwon-token amount sender recipient))
)
(err u0)
)
) | 0xc21e09dc1b652a4ef87894f2af34f9bce54bcf25644b1d8fc888696469f7011c | 19,920 | success |
ruma-v1 |
;; Interface definitions
;; test/mocknet
;; (impl-trait 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-approvable-trait.nft-approvable-trait)
;; (impl-trait 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-trait.nft-trait)
;; mainnet
;; (impl-trait SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ.nft-approvable-trait.nft-approvable-trait)
;; (impl-trait SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
;; contract variables
(define-data-var administrator principal 'SP3QSAJQ4EA8WXEDSRRKMZZ29NH91VZ6C5X88FGZQ)
(define-data-var mint-price uint u1000000)
(define-data-var base-token-uri (string-ascii 256) "https://ruma.risidio.com/mesh/v2/asset/")
(define-data-var mint-counter uint u0)
(define-data-var platform-fee uint u5)
;; constants
(define-constant token-name "params.tokenName")
(define-constant token-symbol "RUMA")
;; Non Fungible Token, modeled after ERC-721 via nft-trait
;; Note this is a basic implementation - no support yet for setting approvals for assets
;; NFT are identified by nft-index (uint) which is tied via a reverse lookup to a real world
;; asset hash - SHA 256 32 byte value. The Asset Hash is used to tie arbitrary real world
;; data to the NFT
(define-non-fungible-token my-nft uint)
;; data structures
(define-map nft-approvals {nft-index: uint} {approval: principal})
(define-map nft-lookup {asset-hash: (buff 32), edition: uint} {nft-index: uint})
(define-map nft-data {nft-index: uint} {asset-hash: (buff 32), meta-data-url: (buff 200), max-editions: uint, edition: uint, edition-cost: uint, mint-block-height: uint, series-original: uint})
(define-map nft-sale-data {nft-index: uint} {sale-type: uint, increment-stx: uint, reserve-stx: uint, amount-stx: uint, bidding-end-time: uint, sale-cycle-index: uint})
(define-map nft-beneficiaries {nft-index: uint} { addresses: (list 10 principal), shares: (list 10 uint) })
(define-map nft-bid-history {nft-index: uint, bid-index: uint} {sale-cycle: uint, bidder: principal, amount: uint, app-timestamp: uint})
(define-map nft-offer-history {nft-index: uint, offer-index: uint} {sale-cycle: uint, offerer: principal, app-timestamp: uint, amount: uint, accepted: uint})
;; counters keep track per NFT of the...
;; a) number of editions minted (1 based index)
;; b) number of offers made (0 based index)
;; c) number of bids made (0 based index)
(define-map nft-offer-counter {nft-index: uint} {offer-counter: uint, sale-cycle: uint})
(define-map nft-edition-counter {nft-index: uint} {edition-counter: uint})
(define-map nft-high-bid-counter {nft-index: uint} {high-bid-counter: uint, sale-cycle: uint})
(define-constant percentage-on-secondary u10)
(define-constant percentage-with-twodp u10000000000)
(define-constant not-allowed (err u10))
(define-constant not-found (err u11))
(define-constant amount-not-set (err u12))
(define-constant seller-not-found (err u13))
(define-constant asset-not-registered (err u14))
(define-constant transfer-error (err u15))
(define-constant not-approved-to-sell (err u16))
(define-constant same-spender-err (err u17))
(define-constant failed-to-mint-err (err u18))
(define-constant edition-counter-error (err u19))
(define-constant edition-limit-reached (err u20))
(define-constant user-amount-different (err u21))
(define-constant failed-to-stx-transfer (err u22))
(define-constant failed-to-close-1 (err u23))
(define-constant failed-refund (err u24))
(define-constant failed-to-close-3 (err u24))
(define-constant cant-pay-mint-price (err u25))
(define-constant editions-error (err u26))
(define-constant payment-error (err u28))
(define-constant payment-address-error (err u33))
(define-constant payment-share-error (err u34))
(define-constant bidding-error (err u35))
(define-constant prevbid-bidding-error (err u36))
(define-constant not-originale (err u37))
(define-constant bidding-opening-error (err u38))
(define-constant bidding-amount-error (err u39))
(define-constant bidding-endtime-error (err u40))
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-constant nft-not-found-err (err u404)) ;; not found
;; interface methods
;; from nft-trait: Last token ID, limited to uint range
;; note decrement as mint counter is the id of the next nft
(define-read-only (get-last-token-id)
(ok (- (var-get mint-counter) u1))
)
;; from nft-trait: URI for metadata associated with the token
(define-read-only (get-token-uri (nftIndex uint))
(ok (some (var-get base-token-uri)))
)
;; from nft-trait: Gets the owner of the 'SPecified token ID.
(define-read-only (get-owner (nftIndex uint))
(ok (nft-get-owner? my-nft nftIndex))
)
;; from nft-trait: Gets the owner of the 'SPecified token ID.
(define-read-only (get-approval (nftIndex uint))
(ok (unwrap! (get approval (map-get? nft-approvals {nft-index: nftIndex})) not-found))
)
;; sets an approval principal - allowed to call transfer on owner behalf.
(define-public (set-approval-for (nftIndex uint) (approval principal))
(if (is-owner nftIndex tx-sender)
(begin
(map-set nft-approvals {nft-index: nftIndex} {approval: approval})
(ok true)
)
nft-not-owned-err
)
)
;; Transfers tokens to a 'SPecified principal.
(define-public (transfer (nftIndex uint) (owner principal) (recipient principal))
(if (and (is-owner-or-approval nftIndex owner) (is-owner-or-approval nftIndex tx-sender))
(match (nft-transfer? my-nft nftIndex owner recipient)
success (ok true)
error (nft-transfer-err error))
nft-not-owned-err)
)
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
(define-private (is-owner (nftIndex uint) (user principal))
(is-eq user (unwrap! (nft-get-owner? my-nft nftIndex) false))
)
(define-private (is-approval (nftIndex uint) (user principal))
(is-eq user (unwrap! (get approval (map-get? nft-approvals {nft-index: nftIndex})) false))
)
(define-private (is-owner-or-approval (nftIndex uint) (user principal))
(if (is-owner nftIndex user) true
(if (is-approval nftIndex user) true false)
)
)
;; public methods
;; --------------
;; the contract administrator can change the contract administrator
(define-public (transfer-administrator (new-administrator principal))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set administrator new-administrator)
(ok true)
)
)
;; the contract administrator can change the transfer fee charged by the contract on sale of tokens
(define-public (change-fee (new-fee uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set platform-fee new-fee)
(ok true)
)
)
;; the contract administrator can change the base uri - where meta data for tokens in this contract
;; are located
(define-public (update-base-token-uri (new-base-token-uri (string-ascii 256)))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set base-token-uri new-base-token-uri)
(ok true)
)
)
;; the contract administrator can change the mint price
(define-public (update-mint-price (new-mint-price uint))
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(var-set mint-price new-mint-price)
(ok true)
)
)
;; The administrator can transfer the balance in the contract to another address
(define-public (transfer-balance (recipient principal))
(let
(
(balance (stx-get-balance (as-contract tx-sender)))
)
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(unwrap! (stx-transfer? balance (as-contract tx-sender) recipient) failed-to-stx-transfer)
(print {evt: "transfer-balance", recipient: recipient, balance: balance})
(ok balance)
)
)
;; adds an offer to the list of offers on an NFT
(define-public (make-offer (nft-index uint) (amount uint) (app-timestamp uint))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerCounter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nft-index}))))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nft-index})) amount-not-set))
)
(map-insert nft-offer-history {nft-index: nft-index, offer-index: offerCounter} {sale-cycle: saleCycleIndex, offerer: tx-sender, app-timestamp: app-timestamp, amount: amount, accepted: u0})
(map-set nft-offer-counter {nft-index: nft-index} {sale-cycle: saleCycleIndex, offer-counter: (+ offerCounter u1)})
(ok (+ offerCounter u1))
)
)
;; accept-offer
;; marks offer as accepted and transfers ownership to the recipient
(define-public (accept-offer (nft-index uint) (offer-index uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nft-index})) not-allowed))
(offerer (unwrap! (get offerer (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(app-timestamp (unwrap! (get app-timestamp (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(sale-cycle (unwrap! (get sale-cycle (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
(amount (unwrap! (get amount (map-get? nft-offer-history {nft-index: nft-index, offer-index: offer-index})) not-allowed))
)
(asserts! (is-eq saleType u3) not-allowed)
(map-set nft-offer-history {nft-index: nft-index, offer-index: offer-index} {sale-cycle: sale-cycle, offerer: offerer, app-timestamp: app-timestamp, amount: amount, accepted: u1})
(ok (transfer nft-index owner recipient))
)
)
;; mint a new token
;; asset-hash: sha256 hash of asset file
;; max-editions: maximum number of editions allowed for this asset
;; royalties: a list of priciple/percentages to be be paid from sale price
;;
;; 1. transfer mint price to the administrator
;; 2. mint the token using built in mint function
;; 3. update the two maps - first contains the data indexed by the nft index, second
;; provides a reverse lookup based on the asset hash - this allows tokens to be located
;; from just a knowledge of the original asset.
;; Note series-original in the case of the original in series is just
;; mintCounter - for editions this provides a safety hook back to the original in cases
;; where the asset hash is unknown (ie cant be found from nft-lookup).
(define-public (mint-token (asset-hash (buff 32)) (metaDataUrl (buff 200)) (maxEditions uint) (editionCost uint) (addresses (list 10 principal)) (shares (list 10 uint)))
(let
(
(mintCounter (var-get mint-counter))
(ahash (get asset-hash (map-get? nft-data {nft-index: (var-get mint-counter)})))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
)
(asserts! (> maxEditions u0) editions-error)
(asserts! (> (stx-get-balance tx-sender) (var-get mint-price)) cant-pay-mint-price)
(asserts! (is-none ahash) asset-not-registered)
;; Note: series original is really for later editions to refer back to this one - this one IS the series original
(map-insert nft-data {nft-index: mintCounter} {asset-hash: asset-hash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: u1, edition-cost: editionCost, mint-block-height: block-height, series-original: mintCounter})
;; Note editions are 1 based and <= maxEditions - the one minted here is #1
(map-insert nft-edition-counter {nft-index: mintCounter} {edition-counter: u2})
;; By default we accept offers - sale type can be changed via the UI.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(map-insert nft-lookup {asset-hash: asset-hash, edition: u1} {nft-index: mintCounter})
;; The payment is split between the nft-beneficiaries with share > 0 they are set per edition
(map-insert nft-beneficiaries {nft-index: mintCounter} {addresses: addresses, shares: shares})
;; finally - mint the NFT and step the counter
(if (is-eq tx-sender (var-get administrator))
(print "mint-token : tx-sender is contract - skipping mint price")
(begin
(unwrap! (stx-transfer? (var-get mint-price) tx-sender (var-get administrator)) failed-to-stx-transfer)
(print "mint-token : tx-sender paid mint price")
)
)
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
(print {evt: "mint-token", nftIndex: mintCounter, owner: tx-sender, amount: (var-get mint-price)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
(define-public (mint-edition (nftIndex uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(maxEditions (unwrap! (get max-editions (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCost (unwrap! (get edition-cost (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(editionCounter (unwrap! (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex})) edition-counter-error))
(thisEdition (default-to u0 (get nft-index (map-get? nft-lookup {asset-hash: ahash, edition: editionCounter}))))
(block-time (unwrap! (get-block-info? time u0) amount-not-set))
(mintCounter (var-get mint-counter))
)
;; can only mint an edition via buy now or bidding - not offers
(asserts! (is-eq thisEdition u0) edition-counter-error)
;; Note - the edition index is 1 based and incremented before insertion in this method - therefore the test is '<=' here!
(asserts! (<= editionCounter maxEditions) edition-limit-reached)
;; This asserts the first one has been minted already - see mint-token.
(asserts! (> editionCounter u1) edition-counter-error)
;; check the buyer has enough funds..
(asserts! (> (stx-get-balance tx-sender) editionCost) cant-pay-mint-price)
;; set max editions so we know where we are in the series
(map-insert nft-data {nft-index: mintCounter} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: editionCounter, edition-cost: editionCost, mint-block-height: block-height, series-original: nftIndex})
;; put the nft index into the list of editions in the look up map
(map-insert nft-lookup {asset-hash: ahash, edition: editionCounter} {nft-index: mintCounter})
;; mint the NFT and update the counter for the next..
(unwrap! (nft-mint? my-nft mintCounter tx-sender) failed-to-mint-err)
;; saleType = 1 (buy now) - split out the payments according to royalties - or roll everything back.
(if (> editionCost u0)
(begin (unwrap! (payment-split nftIndex editionCost tx-sender) failed-to-mint-err) (print "mint-edition : payment split made"))
(print "mint-edition : payment not required")
)
;; (print "mint-edition : payment managed")
;; initialise the sale data - not for sale until the owner sets it.
(map-insert nft-sale-data { nft-index: mintCounter } { sale-cycle-index: u1, sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: (+ block-time u1814400)})
(print {evt: "mint-edition", nftIndex: nftIndex, owner: tx-sender, edition: editionCounter, amount: editionCost})
;; inncrement the mint counter and edition counter ready for the next edition
(map-set nft-edition-counter {nft-index: nftIndex} {edition-counter: (+ u1 editionCounter)})
(var-set mint-counter (+ mintCounter u1))
(ok mintCounter)
)
)
;; allow the owner of the series original to set the cost of minting editions
;; the cost for each edition is taken from the series original and so we need to
;; operate on the the original here - ie nftIndex is the index of thee original
;; and NOT the edition andd only the creator of the series original can change this.
(define-public (set-edition-cost (nftIndex uint) (maxEditions uint) (editionCost uint))
(let
(
(ahash (unwrap! (get asset-hash (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(metaDataUrl (unwrap! (get meta-data-url (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(edition (unwrap! (get edition (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(mintBlockHeight (unwrap! (get mint-block-height (map-get? nft-data {nft-index: nftIndex})) not-allowed))
(seriesOriginal (unwrap! (get series-original (map-get? nft-data {nft-index: nftIndex})) not-allowed))
)
(asserts! (is-owner nftIndex tx-sender) nft-not-owned-err)
(asserts! (is-eq nftIndex seriesOriginal) not-originale)
(ok (map-set nft-data {nft-index: nftIndex} {asset-hash: ahash, meta-data-url: metaDataUrl, max-editions: maxEditions, edition: edition, edition-cost: editionCost, mint-block-height: mintBlockHeight, series-original: seriesOriginal}))
)
)
;; set-sale-data updates the sale type and purchase info for a given NFT. Only the owner can call this method
;; and doing so make the asset transferable by the recipient - on condition of meeting the conditions of sale
;; This is equivalent to the setApprovalForAll method in ERC 721 contracts.
;; Assumption being made here is that all editions have the same sale data associated
(define-public (set-sale-data (nftIndex uint) (sale-type uint) (increment-stx uint) (reserve-stx uint) (amount-stx uint) (bidding-end-time uint))
(let
(
;; before we start... check the hash corresponds to a minted asset
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
)
(asserts! (not (and (> currentAmount u0) (is-eq saleType u2))) bidding-error)
(print {evt: "set-sale-data", nftIndex: nftIndex, saleType: sale-type, increment: increment-stx, reserve: reserve-stx, amount: amount-stx, biddingEndTime: bidding-end-time})
(if (is-owner nftIndex tx-sender)
;; Note - don't override the sale cyle index here as this is a public method and can be called ad hoc. Sale cycle is update at end of sale!
(if (map-set nft-sale-data {nft-index: nftIndex} {sale-cycle-index: saleCycleIndex, sale-type: sale-type, increment-stx: increment-stx, reserve-stx: reserve-stx, amount-stx: amount-stx, bidding-end-time: bidding-end-time})
(ok nftIndex) not-allowed
)
not-allowed
)
)
)
;; buy-now
;; pay royalties and transfer asset ownership to tx-sender.
;; Checks that:
;; a) asset is registered
;; b) on sale via buy now
;; c) amount is set
;;
(define-public (buy-now (nftIndex uint) (owner principal) (recipient principal))
(let
(
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(ahash (get asset-hash (map-get? nft-data {nft-index: nftIndex})))
)
(asserts! (is-some ahash) asset-not-registered)
(asserts! (is-eq saleType u1) not-approved-to-sell)
(asserts! (> amount u0) amount-not-set)
;; Make the royalty payments - then zero out the sale data and register the transfer
;; (print "buy-now : Make the royalty payments")
(print (unwrap! (payment-split nftIndex amount tx-sender) payment-error))
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
;; (print "buy-now : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(print {evt: "buy-now", nftIndex: nftIndex, owner: owner, recipient: recipient, amount: amount})
(nft-transfer? my-nft nftIndex owner recipient)
)
)
;; opening-bid
;; nft-index: unique index for NFT
;; The opening bid in the given sale cycle a given item.
(define-public (opening-bid (nftIndex uint) (bidAmount uint) (appTimestamp uint))
(let
(
(amount (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(biddingEndTime (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(bidCounter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(asserts! (is-eq bidAmount amount) bidding-amount-error)
(asserts! (> biddingEndTime appTimestamp) bidding-endtime-error)
(print "place-bid : sending this much to; ")
(print bidAmount)
(print (as-contract tx-sender))
(print "place-bid : when")
(print appTimestamp)
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {evt: "opening-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: bidAmount})
(ok bidAmount)
)
)
(define-private (get-current-bidder (nftIndex uint) (currentBidIndex uint))
(let
(
(currentBidder (unwrap! (get bidder (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)})) bidding-error))
)
(ok currentBidder)
)
)
(define-private (get-current-bid-amount (nftIndex uint) (currentBidIndex uint))
(if (is-eq currentBidIndex u0)
(ok u0)
(let
(
(currentAmount (default-to u0 (get amount (map-get? nft-bid-history {nft-index: nftIndex, bid-index: (- currentBidIndex u1)}))))
)
(ok currentAmount)
)
)
)
;; place-bid
;; nft-index: unique index for NFT
;; nextBidAmount: amount the user is bidding - i.e the amount display on th place bid button.
(define-public (place-bid (nftIndex uint) (nextBidAmount uint) (appTimestamp uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(amountStart (unwrap! (get amount-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(increment (unwrap! (get increment-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(reserve (unwrap! (get reserve-stx (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
(owner (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err))
)
;; Check the user bid amount is the opening price OR the current bid plus increment
(print "place-bid : assert there is an opening bid - otherwise client calls opening-bid")
(print currentAmount)
(asserts! (> currentAmount u0) user-amount-different)
(asserts! (is-eq nextBidAmount (+ currentAmount increment)) user-amount-different)
;; if (appTimestamp > bidding-end-time) then this is either the winning or a too late bid on the NFT
;; a too late bid will have been rejected as the last bid resets the sale/bidding data on the item.
;; if its the last bid...
;; 1. Refund the currentBid to the bidder
;; 2. move currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
;; (next-bid) we
;; 1. Refund the currentBid to the bidder
;; 2. Insert currentBid to bid history
;; 3. Set the bid in nft-high-bid-counter - note 'set' so we overwrite the previous bid
(if (> appTimestamp bidding-end-time)
(begin
(print {evt: "place-bid-closure", nftIndex: nftIndex, appTimestamp: appTimestamp, biddingEndTime: bidding-end-time, amount: nextBidAmount, reserve: reserve})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-to-stx-transfer)
(if (< nextBidAmount reserve)
;; if this bid is less than reserve & its the last bid then just refund previous bid
(unwrap! (ok true) failed-to-stx-transfer)
(begin
;; WINNING BID - is the FIRST bid after bidding close.
(print "place-bid : Make the royalty payments")
(unwrap! (payment-split nftIndex nextBidAmount tx-sender) payment-error)
(unwrap! (record-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycle u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(print "place-bid : Added internal transfer - transfering nft...")
;; finally transfer ownership to the buyer (note: via the buyers transaction!)
(unwrap! (nft-transfer? my-nft nftIndex owner tx-sender) failed-to-stx-transfer)
)
)
)
(begin
(print {evt: "place-bid-refund", nftIndex: nftIndex, appTimestamp: appTimestamp, biddingEndTime: bidding-end-time, amount: nextBidAmount})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-refund)
(unwrap! (next-bid nftIndex nextBidAmount currentBidIndex appTimestamp saleCycle) failed-to-stx-transfer)
)
)
;;
;; NOTE: Above code will only reconcile IF a bid comes in after 'block-time'
;; We may need a manual trigger to end bidding when this doesn't happen - unless there is a
;; to repond to future events / timeouts that I dont know about.
;;
(print {evt: "place-bid", nftIndex: nftIndex, txSender: tx-sender, appTimestamp: appTimestamp, amount: nextBidAmount})
(ok true)
)
)
;; Mint subsequent editions of the NFT
;; nft-index: the index of the original NFT in this series of editions.
;; The sale data must have been set on the asset before calling this.
;; The amount is split according to the royalties.
;; The nextBidAmount is passed to avoid concurrency issues - amount on the buy/bid button must
;; equal the amount expected by the contract.
;; close-bidding
;; nft-index: index of the NFT
;; closeType: type of closure, values are;
;; 1 = buy now closure - uses the last bid (thats held in escrow) to transfer the item to the bidder and to pay royalties
;; 2 = refund closure - the last bid gets refunded and sale is closed. The item ownership does not change.
;; Note bidding can also be closed automatically - if a bid is received after the bidding end time.
;; In the context of a 'live auction' items have no end time and are closed by the 'auctioneer'.
(define-public (close-bidding (nftIndex uint) (closeType uint))
(let
(
(bidding-end-time (unwrap! (get bidding-end-time (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleType (unwrap! (get sale-type (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(saleCycleIndex (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) failed-to-close-1))
(block-time (unwrap! (get-block-info? time u0) not-allowed))
(currentBidIndex (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
(currentBidder (unwrap! (get-current-bidder nftIndex currentBidIndex) bidding-error))
(currentAmount (unwrap! (get-current-bid-amount nftIndex currentBidIndex) bidding-error))
)
(asserts! (or (is-eq closeType u1) (is-eq closeType u2)) failed-to-close-1)
;; only the owner or administrator can call close
(asserts! (or (is-owner nftIndex tx-sender) (unwrap! (is-administrator) not-allowed)) not-allowed)
;; only the administrator can call close BEFORE the end time - note we use the less accurate
;; but fool proof block time here to prevent owner/client code jerry mandering the close function
(asserts! (or (> block-time bidding-end-time) (unwrap! (is-administrator) failed-to-close-3)) failed-to-close-3)
;; Check for a current bid - if none then just reset the sale data to not selling
(if (is-eq currentAmount u0)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
(if (is-eq closeType u1)
(begin
;; buy now closure - pay and transfer ownership
;; note that the money to pay with is in the contract!
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "from-contract", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount, currentBidIndex: currentBidIndex})
(unwrap! (payment-split nftIndex currentAmount (as-contract tx-sender)) payment-error)
(unwrap! (nft-transfer? my-nft nftIndex (unwrap! (nft-get-owner? my-nft nftIndex) nft-not-owned-err) tx-sender) transfer-error)
)
(begin
;; refund closure - refund the bid and reset sale data
(print {evt: "close-bidding", nftIndex: nftIndex, payType: "refund", txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(unwrap! (refund-bid nftIndex currentBidder currentAmount) failed-refund)
(map-set nft-sale-data { nft-index: nftIndex } { sale-cycle-index: (+ saleCycleIndex u1), sale-type: u0, increment-stx: u0, reserve-stx: u0, amount-stx: u0, bidding-end-time: u0})
)
)
)
(print {evt: "close-bidding", nftIndex: nftIndex, closeType: closeType, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok nftIndex)
)
)
;; read only methods
;; ---------------
(define-read-only (get-administrator)
(var-get administrator))
(define-read-only (is-administrator)
(ok (is-eq (var-get administrator) tx-sender)))
(define-read-only (get-base-token-uri)
(var-get base-token-uri))
(define-read-only (get-mint-counter)
(ok (var-get mint-counter))
)
(define-read-only (get-mint-price)
(var-get mint-price))
(define-read-only (get-token-by-index (nftIndex uint))
(ok (get-all-data nftIndex))
)
(define-read-only (get-beneficiaries (nftIndex uint))
(let
(
(beneficiaries (map-get? nft-beneficiaries {nft-index: nftIndex}))
)
(ok beneficiaries)
)
)
(define-read-only (get-offer-at-index (nftIndex uint) (offerIndex uint))
(let
(
(the-offer (map-get? nft-offer-history {nft-index: nftIndex, offer-index: offerIndex}))
)
(ok the-offer)
)
)
(define-read-only (get-bid-at-index (nftIndex uint) (bidIndex uint))
(let
(
(the-bid (map-get? nft-bid-history {nft-index: nftIndex, bid-index: bidIndex}))
)
(ok the-bid)
)
)
;; Get the edition from a knowledge of the #1 edition and the specific edition number
(define-read-only (get-edition-by-hash (asset-hash (buff 32)) (edition uint))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: edition})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-token-by-hash (asset-hash (buff 32)))
(let
(
(nftIndex (unwrap! (get nft-index (map-get? nft-lookup {asset-hash: asset-hash, edition: u1})) amount-not-set))
)
(ok (get-all-data nftIndex))
)
)
(define-read-only (get-contract-data)
(let
(
(the-administrator (var-get administrator))
(the-mint-price (var-get mint-price))
(the-base-token-uri (var-get base-token-uri))
(the-mint-counter (var-get mint-counter))
(the-platform-fee (var-get platform-fee))
(the-token-name token-name)
(the-token-symbol token-symbol)
)
(ok (tuple (administrator the-administrator)
(mintPrice the-mint-price)
(baseTokenUri the-base-token-uri)
(mintCounter the-mint-counter)
(platformFee the-platform-fee)
(tokenName the-token-name)
(tokenSymbol the-token-symbol)))
)
)
(define-private (get-all-data (nftIndex uint))
(let
(
(the-owner (unwrap-panic (nft-get-owner? my-nft nftIndex)))
(the-token-info (map-get? nft-data {nft-index: nftIndex}))
(the-sale-data (map-get? nft-sale-data {nft-index: nftIndex}))
(the-beneficiary-data (map-get? nft-beneficiaries {nft-index: nftIndex}))
(the-edition-counter (default-to u0 (get edition-counter (map-get? nft-edition-counter {nft-index: nftIndex}))))
(the-offer-counter (default-to u0 (get offer-counter (map-get? nft-offer-counter {nft-index: nftIndex}))))
(the-high-bid-counter (default-to u0 (get high-bid-counter (map-get? nft-high-bid-counter {nft-index: nftIndex}))))
)
(ok (tuple (offerCounter the-offer-counter)
(bidCounter the-high-bid-counter)
(editionCounter the-edition-counter)
(nftIndex nftIndex)
(tokenInfo the-token-info)
(saleData the-sale-data)
(beneficiaryData the-beneficiary-data)
(owner the-owner)
)
)
)
)
(define-read-only (get-sale-data (nftIndex uint))
(match (map-get? nft-sale-data {nft-index: nftIndex})
mySaleData
(ok mySaleData)
not-found
)
)
(define-read-only (get-token-name)
(ok token-name)
)
(define-read-only (get-token-symbol)
(ok token-symbol)
)
(define-read-only (get-balance)
(begin
(asserts! (is-eq (var-get administrator) tx-sender) not-allowed)
(ok (stx-get-balance (as-contract tx-sender)))
)
)
;; private methods
;; ---------------
(define-private (refund-bid (nftIndex uint) (currentBidder principal) (currentAmount uint))
(begin
(unwrap! (as-contract (stx-transfer? currentAmount tx-sender currentBidder)) failed-to-stx-transfer)
(print {evt: "refund-bid", nftIndex: nftIndex, txSender: tx-sender, currentBidder: currentBidder, currentAmount: currentAmount})
(ok true)
)
)
;; need to account for reserve-stx
(define-private (record-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
;; see place-bid for the payment - no need for this (unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {evt: "record-bid", nftIndex: nftIndex, txSender: tx-sender, bidAmount: bidAmount, bidCounter: bidCounter, appTimestamp: appTimestamp, saleCycle: saleCycle})
(ok true)
)
)
(define-private (next-bid (nftIndex uint) (bidAmount uint) (bidCounter uint) (appTimestamp uint) (saleCycle uint))
(begin
(unwrap! (stx-transfer? bidAmount tx-sender (as-contract tx-sender)) failed-to-stx-transfer)
(map-insert nft-bid-history {nft-index: nftIndex, bid-index: bidCounter} {bidder: tx-sender, amount: bidAmount, app-timestamp: appTimestamp, sale-cycle: saleCycle})
(map-set nft-high-bid-counter {nft-index: nftIndex} {high-bid-counter: (+ bidCounter u1), sale-cycle: saleCycle})
(print {appTimestamp: appTimestamp, bidAmount: bidAmount, bidCounter: bidCounter, evt: "next-bid", nftIndex: nftIndex, saleCycle: saleCycle, txSender: tx-sender})
(ok true)
)
)
;; sends payments to each recipient listed in the royalties
;; Note this is called by mint-edition where thee nftIndex actuallt referes to the series orginal and is where the royalties are stored.
(define-private (payment-split (nftIndex uint) (saleAmount uint) (payer principal))
(let
(
(addresses (unwrap! (get addresses (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(shares (unwrap! (get shares (map-get? nft-beneficiaries {nft-index: nftIndex})) failed-to-mint-err))
(saleCycle (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set))
(split u0)
;; If secondary sale (sale-cycle > 1) - the seller gets half the sale value and each royalty payment is half the original amount
(scalor (if (> (unwrap! (get sale-cycle-index (map-get? nft-sale-data {nft-index: nftIndex})) amount-not-set) u1)
percentage-on-secondary u1))
)
(if (is-eq scalor percentage-on-secondary)
;; If secondary sale - pay the seller then split the royalties
(unwrap! (stx-transfer? (/ (* saleAmount (- u100 percentage-on-secondary)) u100) payer (unwrap! (nft-get-owner? my-nft nftIndex) payment-share-error)) transfer-error)
;; Primary sale - split the royalties
true
)
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u0) payment-address-error) (unwrap! (element-at shares u0) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u1) payment-address-error) (unwrap! (element-at shares u1) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u2) payment-address-error) (unwrap! (element-at shares u2) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u3) payment-address-error) (unwrap! (element-at shares u3) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u4) payment-address-error) (unwrap! (element-at shares u4) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u5) payment-address-error) (unwrap! (element-at shares u5) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u6) payment-address-error) (unwrap! (element-at shares u6) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u7) payment-address-error) (unwrap! (element-at shares u7) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u8) payment-address-error) (unwrap! (element-at shares u8) payment-share-error)) payment-share-error))
(+ split (unwrap! (pay-royalty scalor payer saleAmount (unwrap! (element-at addresses u9) payment-address-error) (unwrap! (element-at shares u9) payment-share-error)) payment-share-error))
(print {evt: "payment-split", nftIndex: nftIndex, scalor: scalor, payer: payer, saleAmount: saleAmount, seller: (/ (* saleAmount (- u100 percentage-on-secondary)) u100), txSender: tx-sender})
(ok split)
)
)
;; unit of saleAmount is in Satoshi and the share variable is a percentage (ex for 5% it will be equal to 5)
;; also the scalor is 1 on first purchase - direct from artist and 2 for secondary sales - so the seller gets half the
;; sale value and each royalty address gets half their original amount.
(define-private (pay-royalty (scalor uint) (payer principal) (saleAmount uint) (payee principal) (share uint))
(begin
(if (> share u0)
(let
(
(split (/ (* saleAmount (/ share scalor)) percentage-with-twodp))
)
;; ignore royalty payment if its to the buyer / tx-sender.
(if (not (is-eq tx-sender payee))
(unwrap! (stx-transfer? split payer payee) transfer-error)
(unwrap! (ok true) transfer-error)
)
(print {evt: "pay-royalty-primary", payee: payee, payer: payer, saleAmount: saleAmount, scalor: scalor, share: share, split: split, txSender: tx-sender})
(ok split)
)
(ok u0)
)
)
)
| 0xa52896bd8d3e3f8d31ce124687128f5fbd2deb788f03d0a1f91fa7f69bbf8e48 | 20,076 | success |
swapr-trait | ;; this is an SIP-010 method with an additional functions used by swapr
;; as Clarity does not support "includes", copy the needed functions, and add new ones
(define-trait swapr-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance-of (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
;; additional functions specific to swapr
;; mint function only swapr contract can call
(mint (principal uint) (response bool uint))
;; burn function only swapr contract can call
(burn (principal uint) (response bool uint))
;;
(get-data (principal) (response {
name: (string-ascii 32),
symbol: (string-ascii 32),
decimals: uint,
uri: (optional (string-utf8 256)),
supply: uint,
balance: uint,
} uint))
)
)
| 0x86361b2b4b8f05ba3cb7f9efb559568ae146317e514ee0c72817c6a1a266abf2 | 20,149 | success |
trait-swapr | ;; this is an SIP-010 method with an additional functions used by swapr
;; as Clarity does not support "includes", copy the needed functions, and add new ones
(define-trait swapr-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance-of (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
;; additional functions specific to swapr
;; mint function only swapr contract can call
(mint (principal uint) (response bool uint))
;; burn function only swapr contract can call
(burn (principal uint) (response bool uint))
;;
(get-data (principal) (response {
name: (string-ascii 32),
symbol: (string-ascii 32),
decimals: uint,
uri: (optional (string-utf8 256)),
supply: uint,
balance: uint,
} uint))
)
) | 0x2e8fdb571815c2f2f0dbd50d7a72afbe5fa573e5499cc93cb56c37332bb43819 | 20,150 | success |
swapr | (use-trait sip-010-token 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010.ft-trait)
(use-trait swapr-token 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-trait.swapr-trait)
;; (use-trait sip-010-token .sip-010.ft-trait)
;; (use-trait swapr-token .trait-swapr.swapr-trait)
(define-constant contract-owner 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF)
(define-constant no-liquidity-err (err u61))
;; (define-constant transfer-failed-err (err u62))
(define-constant not-owner-err (err u63))
(define-constant no-fee-to-address-err (err u64))
(define-constant invalid-pair-err (err u65))
(define-constant no-such-position-err (err u66))
(define-constant balance-too-low-err (err u67))
(define-constant too-many-pairs-err (err u68))
(define-constant pair-already-exists-err (err u69))
(define-constant wrong-token-err (err u70))
(define-constant too-much-slippage-err (err u71))
(define-constant transfer-x-failed-err (err u72))
(define-constant transfer-y-failed-err (err u73))
(define-constant value-out-of-range-err (err u74))
(define-constant no-fee-x-err (err u75))
(define-constant no-fee-y-err (err u76))
;; for future use, or debug
(define-constant e10-err (err u20))
(define-constant e11-err (err u21))
(define-constant e12-err (err u22))
(define-map pairs-map
{ pair-id: uint }
{
token-x: principal,
token-y: principal,
}
)
(define-map pairs-data-map
{
token-x: principal,
token-y: principal,
}
{
shares-total: uint,
balance-x: uint,
balance-y: uint,
fee-balance-x: uint,
fee-balance-y: uint,
fee-to-address: (optional principal),
swapr-token: principal,
name: (string-ascii 32),
}
)
;; TODO(psq): replace use of balance-x/balance-y with a call to balance-of(swapr) on the token itself, no write to do actually!!! The transfer is the write, that's cool :)
;; I don't think so anymore?
;; (define-data-var pairs-list (list 2000 uint) (list))
(define-data-var pair-count uint u0)
(define-read-only (get-name (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
)
(ok (get name pair))
)
)
(define-public (get-symbol (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(ok
(concat
(unwrap-panic (as-max-len? (unwrap-panic (contract-call? token-x-trait get-symbol)) u15))
(concat "-"
(unwrap-panic (as-max-len? (unwrap-panic (contract-call? token-y-trait get-symbol)) u15))
)
)
)
)
(define-read-only (get-total-supply (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
)
(ok (get shares-total pair))
)
)
;; get the total number of shares in the pool
(define-read-only (get-shares (token-x principal) (token-y principal))
(ok (get shares-total (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
)
;; get overall balances for the pair
(define-public (get-balances (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
)
(ok (list (get balance-x pair) (get balance-y pair)))
)
)
(define-public (get-data (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (token-swapr-trait <swapr-token>) (owner principal))
(let
(
(token-data (unwrap-panic (contract-call? token-swapr-trait get-data owner)))
(balances (unwrap-panic (get-balances token-x-trait token-y-trait)))
)
(ok (merge token-data { balances: balances }))
)
)
;; since we can't use a constant to refer to contract address, here what x and y are
;; (define-constant x-token 'SP2NC4YKZWM2YMCJV851VF278H9J50ZSNM33P3JM1.my-token)
;; (define-constant y-token 'SP1QR3RAGH3GEME9WV7XB0TZCX6D5MNDQP97D35EH.my-token)
(define-public (add-to-position (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (token-swapr-trait <swapr-token>) (x uint) (y uint))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap-panic (map-get? pairs-data-map { token-x: token-x, token-y: token-y })))
(contract-address (as-contract tx-sender))
(recipient-address tx-sender)
(balance-x (get balance-x pair))
(balance-y (get balance-y pair))
(new-shares
(if (is-eq (get shares-total pair) u0)
(sqrti (* x y)) ;; burn a fraction of initial lp token to avoid attack as described in WP https://uniswap.org/whitepaper.pdf
(/ (* x (get shares-total pair)) balance-x)
)
)
;; TODO(psq): need to calculate y based on x, and only transfer the correct amount
;; without this, people could game the pool by only providing x!!! not nice...
(new-y
(if (is-eq (get shares-total pair) u0)
y
(/ (* x balance-y) balance-x)
)
)
(pair-updated (merge pair {
shares-total: (+ new-shares (get shares-total pair)),
balance-x: (+ balance-x x),
balance-y: (+ balance-y new-y)
}))
)
;; TODO(psq) check if x or y is 0, to calculate proper exchange rate unless shares-total is 0, which would be an error
(asserts! (is-ok (contract-call? token-x-trait transfer x tx-sender contract-address)) transfer-x-failed-err)
(asserts! (is-ok (contract-call? token-y-trait transfer new-y tx-sender contract-address)) transfer-y-failed-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-updated)
(try! (contract-call? token-swapr-trait mint recipient-address new-shares))
(print { object: "pair", action: "liquidity-added", data: pair-updated })
(ok true)
)
)
(define-read-only (get-pair-details (token-x principal) (token-y principal))
(unwrap-panic (map-get? pairs-data-map { token-x: token-x, token-y: token-y }))
)
(define-read-only (get-pair-contracts (pair-id uint))
(unwrap-panic (map-get? pairs-map { pair-id: pair-id }))
)
(define-read-only (get-pair-count)
(ok (var-get pair-count))
)
;; (define-read-only (get-pairs)
;; (ok (map get-pair-contracts (var-get pairs-list)))
;; )
(define-public (create-pair (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (token-swapr-trait <swapr-token>) (pair-name (string-ascii 32)) (x uint) (y uint))
;; TOOD(psq): add creation checks, then create map before proceeding to add-to-position
;; check neither x,y or y,x exists`
(let
(
(name-x (unwrap-panic (contract-call? token-x-trait get-name)))
(name-y (unwrap-panic (contract-call? token-y-trait get-name)))
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair-id (+ (var-get pair-count) u1))
(pair-data {
shares-total: u0,
balance-x: u0,
balance-y: u0,
fee-balance-x: u0,
fee-balance-y: u0,
fee-to-address: none,
swapr-token: (contract-of token-swapr-trait),
name: pair-name,
})
)
(asserts!
(and
(is-none (map-get? pairs-data-map { token-x: token-x, token-y: token-y }))
(is-none (map-get? pairs-data-map { token-x: token-y, token-y: token-x }))
)
pair-already-exists-err
)
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-data)
(map-set pairs-map { pair-id: pair-id } { token-x: token-x, token-y: token-y })
;; (var-set pairs-list (unwrap! (as-max-len? (append (var-get pairs-list) pair-id) u2000) too-many-pairs-err))
(var-set pair-count pair-id)
(try! (add-to-position token-x-trait token-y-trait token-swapr-trait x y))
(print { object: "pair", action: "created", data: pair-data })
(ok true)
)
)
;; ;; reduce the amount of liquidity the sender provides to the pool
;; ;; to close, use u100
(define-public (reduce-position (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (token-swapr-trait <swapr-token>) (percent uint))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
(balance-x (get balance-x pair))
(balance-y (get balance-y pair))
(shares (unwrap-panic (contract-call? token-swapr-trait get-balance-of tx-sender)))
(shares-total (get shares-total pair))
(contract-address (as-contract tx-sender))
(sender tx-sender)
(withdrawal (/ (* shares percent) u100))
(withdrawal-x (/ (* withdrawal balance-x) shares-total))
(withdrawal-y (/ (* withdrawal balance-y) shares-total))
(pair-updated
(merge pair
{
shares-total: (- shares-total withdrawal),
balance-x: (- (get balance-x pair) withdrawal-x),
balance-y: (- (get balance-y pair) withdrawal-y)
}
)
)
)
(asserts! (<= percent u100) value-out-of-range-err)
(asserts! (is-ok (as-contract (contract-call? token-x-trait transfer withdrawal-x contract-address sender))) transfer-x-failed-err)
(asserts! (is-ok (as-contract (contract-call? token-y-trait transfer withdrawal-y contract-address sender))) transfer-y-failed-err)
;; (unwrap-panic (decrease-shares token-x token-y tx-sender withdrawal)) ;; should never fail, you know...
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-updated)
;; TODO(psq): use burn
;; (unwrap-panic (contract-call? token-swapr-trait transfer withdrawal tx-sender contract-address)) ;; transfer back to swapr, wish there was a burn instead...
(try! (contract-call? token-swapr-trait burn tx-sender withdrawal))
(print { object: "pair", action: "liquidity-removed", data: pair-updated })
(ok (list withdrawal-x withdrawal-y))
)
)
;; exchange known dx of x-token for whatever dy of y-token based on current liquidity, returns (dx dy)
;; the swap will not happen if can't get at least min-dy back
(define-public (swap-x-for-y (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (dx uint) (min-dy uint))
;; calculate dy
;; calculate fee on dx
;; transfer
;; update balances
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
(balance-x (get balance-x pair))
(balance-y (get balance-y pair))
(contract-address (as-contract tx-sender))
(sender tx-sender)
(dy (/ (* u997 balance-y dx) (+ (* u1000 balance-x) (* u997 dx)))) ;; overall fee is 30 bp, either all for the pool, or 25 bp for pool and 5 bp for operator
(fee (/ (* u5 dx) u10000)) ;; 5 bp
(pair-updated
(merge pair
{
balance-x: (+ (get balance-x pair) dx),
balance-y: (- (get balance-y pair) dy),
fee-balance-x: (if (is-some (get fee-to-address pair)) ;; only collect fee when fee-to-address is set
(+ fee (get fee-balance-x pair))
(get fee-balance-x pair))
}
)
)
)
(asserts! (< min-dy dy) too-much-slippage-err)
;; TODO(psq): check that the amount transfered in matches the amount requested
(asserts! (is-ok (contract-call? token-x-trait transfer dx sender contract-address)) transfer-x-failed-err)
(asserts! (is-ok (as-contract (contract-call? token-y-trait transfer dy contract-address sender))) transfer-y-failed-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-updated)
(print { object: "pair", action: "swap-x-for-y", data: pair-updated })
(ok (list dx dy))
)
)
;; exchange known dy for whatever dx based on liquidity, returns (dx dy)
;; the swap will not happen if can't get at least min-dx back
(define-public (swap-y-for-x (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (dy uint) (min-dx uint))
;; calculate dx
;; calculate fee on dy
;; transfer
;; update balances
(let ((token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
(balance-x (get balance-x pair))
(balance-y (get balance-y pair))
(contract-address (as-contract tx-sender))
(sender tx-sender)
;; check formula, vs x-for-y???
(dx (/ (* u997 balance-x dy) (+ (* u1000 balance-y) (* u997 dy)))) ;; overall fee is 30 bp, either all for the pool, or 25 bp for pool and 5 bp for operator
(fee (/ (* u5 dy) u10000)) ;; 5 bp
(pair-updated (merge pair {
balance-x: (- (get balance-x pair) dx),
balance-y: (+ (get balance-y pair) dy),
fee-balance-y: (if (is-some (get fee-to-address pair)) ;; only collect fee when fee-to-address is set
(+ fee (get fee-balance-y pair))
(get fee-balance-y pair))
})))
(asserts! (< min-dx dx) too-much-slippage-err)
;; TODO(psq): check that the amount transfered in matches the amount requested
(asserts! (is-ok (as-contract (contract-call? token-x-trait transfer dx contract-address sender))) transfer-x-failed-err)
(asserts! (is-ok (contract-call? token-y-trait transfer dy sender contract-address)) transfer-y-failed-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-updated)
(print { object: "pair", action: "swap-y-for-x", data: pair-updated })
(ok (list dx dy))
)
)
;; ;; activate the contract fee for swaps by setting the collection address, restricted to contract owner
(define-public (set-fee-to-address (token-x principal) (token-y principal) (address principal))
(let ((pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y }
{
shares-total: (get shares-total pair),
balance-x: (get balance-y pair),
balance-y: (get balance-y pair),
fee-balance-x: (get fee-balance-y pair),
fee-balance-y: (get fee-balance-y pair),
fee-to-address: (some address),
name: (get name pair),
swapr-token: (get swapr-token pair),
}
)
(ok true)
)
)
;; ;; clear the contract fee addres
;; ;; TODO(psq): if there are any collected fees, prevent this from happening, as the fees can no longer be collect with `collect-fees`
(define-public (reset-fee-to-address (token-x principal) (token-y principal))
(let ((pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y }
{
shares-total: (get shares-total pair),
balance-x: (get balance-x pair),
balance-y: (get balance-y pair),
fee-balance-x: (get fee-balance-y pair),
fee-balance-y: (get fee-balance-y pair),
fee-to-address: none,
name: (get name pair),
swapr-token: (get swapr-token pair),
}
)
(ok true)
)
)
;; ;; get the current address used to collect a fee
(define-read-only (get-fee-to-address (token-x principal) (token-y principal))
(let ((pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
(ok (get fee-to-address pair))
)
)
;; ;; get the amount of fees charged on x-token and y-token exchanges that have not been collected yet
(define-read-only (get-fees (token-x principal) (token-y principal))
(let ((pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
(ok (list (get fee-balance-x pair) (get fee-balance-y pair)))
)
)
;; ;; send the collected fees the fee-to-address
(define-public (collect-fees (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(contract-address (as-contract tx-sender))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
(address (unwrap! (get fee-to-address pair) no-fee-to-address-err))
(fee-x (get fee-balance-x pair))
(fee-y (get fee-balance-y pair))
)
(asserts! (is-eq fee-x u0) no-fee-x-err)
(asserts! (is-ok (as-contract (contract-call? token-x-trait transfer fee-x contract-address address))) transfer-x-failed-err)
(asserts! (is-eq fee-y u0) no-fee-y-err)
(asserts! (is-ok (as-contract (contract-call? token-y-trait transfer fee-y contract-address address))) transfer-y-failed-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y }
{
shares-total: (get shares-total pair),
balance-x: (get balance-x pair),
balance-y: (get balance-y pair),
fee-balance-x: u0,
fee-balance-y: u0,
fee-to-address: (get fee-to-address pair),
name: (get name pair),
swapr-token: (get swapr-token pair),
}
)
(ok (list fee-x fee-y))
)
)
| 0xf231b86f72718ecbb5f49702959aab0de6d9d9ffcf5f4045b37c1bc249390ce5 | 20,151 | success |
narangd-token |
;; sws-token-01
;; we implement the sip-010
;; In mainnet use https://explorer.stacks.co/txid/SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-10-ft-standard
;; for testnet
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010.ft-trait)
;; (impl-trait .sip-010.ft-trait)
;; constants
;;
(define-fungible-token narangd-token)
(define-constant contract-owner 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF)
(define-constant not-owner-err (err u63))
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance narangd-token owner))
)
;; returns the total number of tokens
(define-read-only (get-total-supply)
(ok (ft-get-supply narangd-token))
)
;; returns the token name
(define-read-only (get-name)
(ok "Narangd Token")
)
(define-read-only (get-symbol)
(ok "NAR")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u3) ;; because we can, and interesting for testing wallets and other clients
)
(define-read-only (get-token-uri)
(ok (some u"empty"))
)
;; data maps and vars
;;
;; private functions
;;
(define-public (owner-mint (account principal) (amount uint))
(if (<= amount u0)
(err u0)
(begin
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(ft-mint? narangd-token amount account)
)
)
)
;; public functions
;;
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (>= (ft-get-balance narangd-token sender) amount)
(begin
(print "narangd.transfer")
(print amount)
(print tx-sender)
(print recipient)
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(print (ft-transfer? narangd-token amount sender recipient))
)
(err u0)
)
)
(ft-mint? plaid u1000000000 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF)
;; (contract-call? .sws-token-01 get-name)
;; (contract-call? .sws-token-01 owner-mint 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA u10)
;; (contract-call? .sws-token-01 get-balance-of 'ST23DAB333A5CPFXNK13E5YMX1DZJ07112QA7HWHA) | 0x6d26a7c2e5268d2b6addfcc098adf2480536c2944ecf8e4da2a5fbbb44dd094f | 20,151 | abort_by_response |
stx-token | ;; wrap the native STX token into an SRC20 compatible token to be usable along other tokens
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010.ft-trait)
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(begin
(ok (print (stx-get-balance owner)))
)
)
(define-read-only (get-total-supply)
(ok stx-liquid-supply)
)
;; returns the token name
(define-read-only (get-name)
(ok "STX")
)
(define-read-only (get-symbol)
(ok "STX")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6)
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/stx.json"))
)
;; {
;; "name":"STX",
;; "description":"STX token, as a SIP-010 compatible token",
;; "image":"https://swapr.finance/tokens/stx.png",
;; "vector":"https://swapr.finance/tokens/stx.svg"
;; }
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(stx-transfer? amount tx-sender recipient)
)
)
| 0xed227e9c49257895bf5bc9aada2246e840b3820308a767811561483d64501853 | 20,151 | success |
narangd-token | (impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010.ft-trait)
;; (impl-trait .sip-010.ft-trait)
;; constants
;;
(define-fungible-token narangd-token)
(define-constant contract-owner 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF)
(define-constant not-owner-err (err u63))
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance narangd-token owner))
)
;; returns the total number of tokens
(define-read-only (get-total-supply)
(ok (ft-get-supply narangd-token))
)
;; returns the token name
(define-read-only (get-name)
(ok "Narangd Token")
)
(define-read-only (get-symbol)
(ok "NAR")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u3) ;; because we can, and interesting for testing wallets and other clients
)
(define-read-only (get-token-uri)
(ok (some u"empty"))
)
;; data maps and vars
;;
;; private functions
;;
(define-public (owner-mint (account principal) (amount uint))
(if (<= amount u0)
(err u0)
(begin
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(ft-mint? narangd-token amount account)
)
)
)
;; public functions
;;
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(if (>= (ft-get-balance narangd-token sender) amount)
(begin
(print "narangd.transfer")
(print amount)
(print tx-sender)
(print recipient)
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(print (ft-transfer? narangd-token amount sender recipient))
)
(err u0)
)
) | 0x6b4f3b33414c46047d99a4dece4474b4a0c894a29948a34698374a91e860aab2 | 20,157 | success |
sws-nar-token | ;; ;; we implement the sip-010 + a mint function
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-trait.swapr-trait)
;; (impl-trait .trait-swapr.swapr-trait)
;; ;; we can use an ft-token here, so use it!
(define-fungible-token sws-nar-token)
(define-constant no-acccess-err u40)
;; implement all functions required by sip-010
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(ft-transfer? sws-nar-token amount tx-sender recipient)
)
)
(define-read-only (get-name)
(ok "SWS NAR swapr")
)
(define-read-only (get-symbol)
(ok "SWS-NAR-swapr")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6) ;; arbitrary, or ok?
)
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance sws-nar-token owner))
)
(define-read-only (get-total-supply)
(ok (ft-get-supply sws-nar-token))
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/plaid-stx-token.json"))
)
;; {
;; "name":"Plaid-STX",
;; "description":"Plaid-STX swapr token",
;; "image":"https://swapr.finance/tokens/plaid-stx.png",
;; "vector":"https://swapr.finance/tokens/plaid-stx.svg"
;; }
;; one stop function to gather all the data relevant to the swapr token in one call
(define-read-only (get-data (owner principal))
(ok {
name: (unwrap-panic (get-name)),
symbol: (unwrap-panic (get-symbol)),
decimals: (unwrap-panic (get-decimals)),
uri: (unwrap-panic (get-token-uri)),
supply: (unwrap-panic (get-total-supply)),
balance: (unwrap-panic (get-balance-of owner))
})
)
;; the extra mint method used by swapr when adding liquidity
;; can only be used by swapr main contract
(define-public (mint (recipient principal) (amount uint))
(begin
(print "token-swapr.mint")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr) (err no-acccess-err))
(ft-mint? sws-nar-token amount recipient)
)
)
;; the extra burn method used by swapr when removing liquidity
;; can only be used by swapr main contract
(define-public (burn (recipient principal) (amount uint))
(begin
(print "token-swapr.burn")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr) (err no-acccess-err))
(ft-burn? sws-nar-token amount recipient)
)
)
| 0x3d2156a552d53a21c2a2ce423da19cd69d98f0cc39c0d6a842f766c2c00c22a7 | 20,159 | success |
nft-trait | (define-trait nft-trait
(
;; Last token ID, limited to uint range
(get-last-token-id () (response uint uint))
;; URI for metadata associated with the token
(get-token-uri (uint) (response (optional (string-ascii 256)) uint))
;; Owner of a given token identifier
(get-owner (uint) (response (optional principal) uint))
;; Transfer from the sender to a new principal
(transfer (uint principal principal) (response bool uint))
)
) | 0x8597b42f6535c134604fb308876a0c46967c3eabd2aa247473b26e2468a19d93 | 20,182 | success |
swag-1000 | (impl-trait 'SPPEYAEM28YFZ2SJWTZRFK1B6MAZV09PB0TQPDR.nft-trait.nft-trait)
(define-non-fungible-token swag-1000 uint)
;; Limited to first 1000 users
(define-constant max-tokens u1000)
;; Error handling
(define-constant nft-max-reached (err u403)) ;; no more tokens availabale
(define-constant nft-not-owned-err (err u401)) ;; unauthorized
(define-constant nft-not-found-err (err u404)) ;; not found
(define-constant sender-equals-recipient-err (err u405)) ;; method not allowed
(define-constant nft-exists-err (err u409)) ;; conflict
(define-private (nft-transfer-err (code uint))
(if (is-eq u1 code)
nft-not-owned-err
(if (is-eq u2 code)
sender-equals-recipient-err
(if (is-eq u3 code)
nft-not-found-err
(err code)))))
(define-private (nft-mint-err (code uint))
(if (is-eq u1 code)
nft-exists-err
(err code)))
;; Storage
(define-map tokens-count principal uint)
(define-data-var last-id uint u0)
;; Transfers tokens to a specified principal.
(define-public (transfer (token-id uint) (sender principal) (recipient principal))
(if (and
(is-eq tx-sender sender))
(match (nft-transfer? swag-1000 token-id sender recipient)
success (ok success)
error (nft-transfer-err error))
nft-not-owned-err))
;; Claim a new swag-1000-nft token.
(define-public (claim-swag)
(if
(and
(< (var-get last-id) max-tokens)
(is-eq (balance-of tx-sender) u0))
(ok (mint tx-sender))
(err nft-max-reached)))
;; Gets the owner of the specified token ID.
(define-read-only (get-owner (token-id uint))
(ok (nft-get-owner? swag-1000 token-id)))
;; Gets the last token ID.
(define-read-only (get-last-token-id)
(ok (var-get last-id)))
(define-read-only (get-token-uri (token-id uint))
(ok (some "https://docs.stacks.co/")))
(define-read-only (get-meta (token-id uint))
(ok (some {name: "Clarity Developer OG", uri: "https://bafybeif4p2ukltj5eofwriclz4ru3p7izitprrs7a2rjhtp6qat673wagu.ipfs.dweb.link/", mime-type: "video/webm"})))
(define-read-only (get-nft-meta)
(ok (some {name: "Clarity Developer OG", uri: "https://bafybeif4p2ukltj5eofwriclz4ru3p7izitprrs7a2rjhtp6qat673wagu.ipfs.dweb.link/", mime-type: "video/webm"})))
;; Internal - Gets the amount of tokens owned by the specified address.
(define-private (balance-of (account principal))
(default-to u0 (map-get? tokens-count account)))
;; Internal - Register token
(define-private (mint (new-owner principal))
(let ((current-balance (balance-of new-owner)) (next-id (+ u1 (var-get last-id))))
(match (nft-mint? swag-1000 next-id new-owner)
success
(begin
(map-set tokens-count
new-owner
(+ u1 current-balance))
(var-set last-id next-id)
(ok success))
error (nft-mint-err error)))) | 0x7246cfb663ddd90041781919961a131938d34345879d708ed7d855039c70b84d | 20,184 | success |
boomboxes-cycle-12 | (impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
(define-non-fungible-token b-12 uint)
(define-constant dplyr tx-sender)
(define-constant accnt (as-contract tx-sender))
(define-constant px-addr {hashbytes: 0x13effebe0ea4bb45e35694f5a15bb5b96e851afb, version: 0x01})
(define-constant minimum-amount u100000000)
(define-constant time-limit u690950)
(define-data-var last-id uint u0)
(define-data-var start (optional uint) none)
(define-data-var total-stacked uint u0)
(define-map meta uint
(tuple
(stacker principal)
(amount-ustx uint)
(until-burn-ht (optional uint))
(stacked-ustx (optional uint))
(reward (optional uint))))
(define-map lookup principal uint)
(define-private (pox-delegate-stx-and-stack (amount-ustx uint) (until-burn-ht (optional uint)))
(begin
(let ((ignore-result-revoke (contract-call? 'SP000000000000000000002Q6VF78.pox revoke-delegate-stx))
(start-block-ht (+ burn-block-height u1))
(locking-cycles u1))
(match (contract-call? 'SP000000000000000000002Q6VF78.pox delegate-stx amount-ustx accnt until-burn-ht none)
success
(let ((stacker tx-sender))
(match (as-contract (contract-call? 'SP000000000000000000002Q6VF78.pox delegate-stack-stx stacker amount-ustx px-addr start-block-ht locking-cycles))
stack-success (ok stack-success)
stack-error (print (err (to-uint stack-error)))))
error (err (to-uint error))))))
(define-private (mint-and-delegatedly-stack (stacker principal) (amount-ustx uint) (until-burn-ht (optional uint)))
(let
((id (+ u1 (var-get last-id))))
(asserts! (>= amount-ustx minimum-amount) err-delegate-below-minimum)
(asserts! (< burn-block-height time-limit) err-delegate-too-late)
(asserts! (>= (stx-get-balance tx-sender) amount-ustx) err-not-enough-funds)
(var-set last-id id)
(match (pox-delegate-stx-and-stack amount-ustx until-burn-ht)
success-pox
(match (nft-mint? b-12 id stacker)
success-mint
(begin
(asserts! (map-insert lookup stacker id) err-map-function-failed)
(asserts! (map-insert meta id
{stacker: stacker, amount-ustx: amount-ustx, stacked-ustx: (some (get lock-amount success-pox)), until-burn-ht: until-burn-ht, reward: none})
err-map-function-failed)
(ok {id: id, pox: success-pox}))
error-minting (err-nft-mint error-minting))
error-pox (err error-pox))))
(define-public (delegate-stx (amount-ustx uint) (stacker principal) (until-burn-ht (optional uint)) (pox-addr (optional (tuple (hashbytes (buff 20)) (version (buff 1))))))
(if (and
(or (is-eq stacker tx-sender) (is-eq stacker contract-caller))
(is-none (map-get? lookup stacker)))
(mint-and-delegatedly-stack stacker amount-ustx until-burn-ht)
err-delegate-invalid-stacker))
;; function for pool admins
(define-private (get-total (stack-result (response (tuple (lock-amount uint) (stacker principal) (unlock-burn-height uint)) (tuple (kind (string-ascii 32)) (code uint))))
(total uint))
(match stack-result
details (+ total (get lock-amount details))
error total))
(define-private (update-meta (id uint) (stacked-ustx uint))
(match (map-get? meta id)
entry (map-set meta id {
stacker: (get stacker entry),
amount-ustx: (get amount-ustx entry),
until-burn-ht: (get until-burn-ht entry),
stacked-ustx: (some stacked-ustx),
reward: (get reward entry)})
false))
(define-public (stack-aggregation-commit (reward-cycle uint))
(if (> burn-block-height time-limit)
(match (as-contract (contract-call? 'SP000000000000000000002Q6VF78.pox stack-aggregation-commit px-addr reward-cycle))
success (ok success)
error (err-pox-stack-aggregation-commit error))
err-commit-too-early))
(define-read-only (nft-details (nft-id uint))
(ok {stacked-ustx: (unwrap! (unwrap! (get stacked-ustx (map-get? meta nft-id)) err-invalid-asset-id) err-invalid-asset-id),
owner: (unwrap! (nft-get-owner? b-12 nft-id) err-no-asset-owner)}))
(define-read-only (nft-details-at-block (nft-id uint) (stacks-tip uint))
(match (get-block-info? id-header-hash stacks-tip)
ihh (print (at-block (print ihh) (nft-details nft-id)))
err-invalid-stacks-tip))
(define-private (payout-nft (nft-id uint) (ctx (tuple (reward-ustx uint) (total-ustx uint) (stx-from principal) (pay-stacks-tip uint) (result (list 750 (response bool uint))))))
(let ((reward-ustx (get reward-ustx ctx))
(total-ustx (get total-ustx ctx))
(stx-from (get stx-from ctx))
(stacks-tip (get pay-stacks-tip ctx)))
(let (
(transfer-result
(match (nft-details-at-block nft-id stacks-tip)
entry (let ((reward-amount (/ (* reward-ustx (get stacked-ustx entry)) total-ustx)))
(match (stx-transfer? reward-amount stx-from (get owner entry))
success-stx-transfer (ok true)
error-stx-transfer (err-stx-transfer error-stx-transfer)))
error (err error))))
{reward-ustx: reward-ustx, total-ustx: total-ustx, stx-from: stx-from, pay-stacks-tip: stacks-tip,
result: (unwrap-panic (as-max-len? (append (get result ctx) transfer-result) u750))})))
(define-private (sum-stacked-ustx (nft-id uint) (total uint))
(match (map-get? meta nft-id)
entry (match (get stacked-ustx entry)
amount (+ total amount)
total)
total))
(define-read-only (get-total-stacked-ustx (nfts (list 750 uint)))
(fold sum-stacked-ustx nfts u0))
(define-read-only (get-total-stacked-ustx-at-block (nfts (list 750 uint)) (stacks-tip uint))
(match (get-block-info? id-header-hash stacks-tip)
ihh (at-block ihh (ok (get-total-stacked-ustx nfts)))
err-invalid-stacks-tip))
(define-public (payout (reward-ustx uint) (nfts (list 750 uint)) (pay-stacks-tip uint))
(match (get-total-stacked-ustx-at-block nfts pay-stacks-tip)
total-ustx (ok (fold payout-nft nfts {reward-ustx: reward-ustx, total-ustx: total-ustx, stx-from: tx-sender, pay-stacks-tip: pay-stacks-tip, result: (list)}))
error (err error)))
(define-read-only (get-total-stacked)
(var-get total-stacked))
(define-public (allow-contract-caller (this-contract principal))
(if (is-eq tx-sender dplyr)
(as-contract (contract-call? 'SP000000000000000000002Q6VF78.pox allow-contract-caller this-contract none))
(err 403)))
;; NFT functions
(define-public (transfer (id uint) (sender principal) (recipient principal))
(if (or (is-eq sender tx-sender) (is-eq sender contract-caller))
(match (nft-transfer? b-12 id sender recipient)
success (ok success)
error (err-nft-transfer error))
err-not-allowed-sender))
(define-read-only (get-owner (id uint))
(ok (nft-get-owner? b-12 id)))
(define-read-only (get-owner-raw? (id uint))
(nft-get-owner? b-12 id))
(define-read-only (get-last-token-id)
(ok (var-get last-id)))
(define-read-only (last-token-id-raw)
(var-get last-id))
(define-read-only (get-token-uri (id uint))
(ok (some "https://cloudflare-ipfs.com/ipfs/bafkreidmfmsjiqunj4tkln57ozw2yhazufqv63j5zohhsqchwol6lznsfy")))
;; error handling
(define-constant err-nft-not-owned (err u401)) ;; unauthorized
(define-constant err-not-allowed-sender (err u403)) ;; forbidden
(define-constant err-nft-not-found (err u404)) ;; not found
(define-constant err-sender-equals-recipient (err u405)) ;; method not allowed
(define-constant err-nft-exists (err u409)) ;; conflict
(define-constant err-not-enough-funds (err u4021)) ;; payment required
(define-constant err-amount-not-positive (err u4022)) ;; payment required
(define-constant err-map-function-failed (err u601))
(define-constant err-invalid-asset-id (err u602))
(define-constant err-no-asset-owner (err u603))
(define-constant err-delegate-below-minimum (err u604))
(define-constant err-delegate-invalid-stacker (err u605))
(define-constant err-delegate-too-late (err u606))
(define-constant err-commit-too-early (err u607))
(define-constant err-invalid-stacks-tip (err u608))
(define-map err-strings (response uint uint) (string-ascii 32))
(map-insert err-strings err-nft-not-owned "nft-not-owned")
(map-insert err-strings err-not-allowed-sender "not-allowed-sender")
(map-insert err-strings err-nft-not-found "nft-not-found")
(map-insert err-strings err-sender-equals-recipient "sender-equals-recipient")
(map-insert err-strings err-nft-exists "nft-exists")
(map-insert err-strings err-map-function-failed "map-function-failed")
(map-insert err-strings err-invalid-asset-id "invalid-asset-id")
(map-insert err-strings err-no-asset-owner "no-asset-owner")
(map-insert err-strings err-delegate-below-minimum "delegate-below-minimum")
(map-insert err-strings err-delegate-invalid-stacker "delegate-invalid-stacker")
(map-insert err-strings err-delegate-too-late "delegate-too-late")
(map-insert err-strings err-commit-too-early "commit-too-early")
(map-insert err-strings err-invalid-stacks-tip "invalid-stacks-tip")
(define-private (err-pox-stack-aggregation-commit (code int))
(err (to-uint (* 1000 code))))
(define-private (err-stx-transfer (code uint))
(if (is-eq u1 code)
err-not-enough-funds
(if (is-eq u2 code)
err-sender-equals-recipient
(if (is-eq u3 code)
err-amount-not-positive
(if (is-eq u4 code)
err-not-allowed-sender
(err code))))))
(define-private (err-nft-transfer (code uint))
(if (is-eq u1 code)
err-nft-not-owned
(if (is-eq u2 code)
err-sender-equals-recipient
(if (is-eq u3 code)
err-nft-not-found
(err code)))))
(define-private (err-nft-mint (code uint))
(if (is-eq u1 code)
err-nft-exists
(err code)))
(define-read-only (get-errstr (code uint))
(unwrap! (map-get? err-strings (err code)) "unknown-error")) | 0x5d8f968111be4556a13d8d0d25f39d998a749a982d673ae6ba7180ee7ccf1f62 | 20,185 | success |
swapr-trait-v0a | ;; this is an SIP-010 method with an additional functions used by swapr
;; as Clarity does not support "includes", copy the needed functions, and add new ones
(define-trait swapr-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance-of (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
;; additional functions specific to swapr
;; mint function only swapr contract can call
(mint (principal uint) (response bool uint))
;; burn function only swapr contract can call
(burn (principal uint) (response bool uint))
;;
(get-data (principal) (response {
name: (string-ascii 32),
symbol: (string-ascii 32),
decimals: uint,
uri: (optional (string-utf8 256)),
supply: uint,
balance: uint,
} uint))
)
)
| 0xb2d8c83a14ce6436314346c34a103d9fe0c6d88ab6b16f55064599593afeed3a | 20,250 | success |
sip-010-v0a | ;; sip-010 trait
;; use https://explorer.stacks.co/txid/SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-10-ft-standard
(define-trait ft-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance-of (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
) | 0x699e7d61a3c9825532bdeb04ac0fcee1ec1b1e3d250625eb57a828b2d4f0a559 | 20,250 | success |
restricted-token-trait-v0a | (define-trait restricted-token-trait
(
;; Called to detect if a transfer restriction will take place. Returns the
;; error code that explains why the transfer failed.
(detect-transfer-restriction (uint principal principal) (response uint uint))
;; Returns human readable string for a specific transfer restriction error code
;; which is returned from (detect-transfer-restriction).
;; This is a convenience function for end user wallets.
(message-for-restriction (uint) (response (string-ascii 1024) uint))
)
)
| 0xe77dcdcdc69d4f6f8737b9e5856441785e8a885191688f77fef228f29af03e35 | 20,252 | success |
swapr-v0a | (use-trait sip-010-token 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010-v0a.ft-trait)
(use-trait swapr-token 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-trait-v0a.swapr-trait)
(define-constant contract-owner 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF)
(define-constant no-liquidity-err (err u61))
;; (define-constant transfer-failed-err (err u62))
(define-constant not-owner-err (err u63))
(define-constant no-fee-to-address-err (err u64))
(define-constant invalid-pair-err (err u65))
(define-constant no-such-position-err (err u66))
(define-constant balance-too-low-err (err u67))
(define-constant too-many-pairs-err (err u68))
(define-constant pair-already-exists-err (err u69))
(define-constant wrong-token-err (err u70))
(define-constant too-much-slippage-err (err u71))
(define-constant transfer-x-failed-err (err u72))
(define-constant transfer-y-failed-err (err u73))
(define-constant value-out-of-range-err (err u74))
(define-constant no-fee-x-err (err u75))
(define-constant no-fee-y-err (err u76))
;; for future use, or debug
(define-constant e10-err (err u20))
(define-constant e11-err (err u21))
(define-constant e12-err (err u22))
(define-map pairs-map
{ pair-id: uint }
{
token-x: principal,
token-y: principal,
}
)
(define-map pairs-data-map
{
token-x: principal,
token-y: principal,
}
{
shares-total: uint,
balance-x: uint,
balance-y: uint,
fee-balance-x: uint,
fee-balance-y: uint,
fee-to-address: (optional principal),
swapr-token: principal,
name: (string-ascii 32),
}
)
;; TODO(psq): replace use of balance-x/balance-y with a call to balance-of(swapr) on the token itself, no write to do actually!!! The transfer is the write, that's cool :)
;; I don't think so anymore?
;; (define-data-var pairs-list (list 2000 uint) (list))
(define-data-var pair-count uint u0)
(define-read-only (get-name (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
)
(ok (get name pair))
)
)
(define-public (get-symbol (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(ok
(concat
(unwrap-panic (as-max-len? (unwrap-panic (contract-call? token-x-trait get-symbol)) u15))
(concat "-"
(unwrap-panic (as-max-len? (unwrap-panic (contract-call? token-y-trait get-symbol)) u15))
)
)
)
)
(define-read-only (get-total-supply (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
)
(ok (get shares-total pair))
)
)
;; get the total number of shares in the pool
(define-read-only (get-shares (token-x principal) (token-y principal))
(ok (get shares-total (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
)
;; get overall balances for the pair
(define-public (get-balances (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
)
(ok (list (get balance-x pair) (get balance-y pair)))
)
)
(define-public (get-data (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (token-swapr-trait <swapr-token>) (owner principal))
(let
(
(token-data (unwrap-panic (contract-call? token-swapr-trait get-data owner)))
(balances (unwrap-panic (get-balances token-x-trait token-y-trait)))
)
(ok (merge token-data { balances: balances }))
)
)
;; since we can't use a constant to refer to contract address, here what x and y are
;; (define-constant x-token 'SP2NC4YKZWM2YMCJV851VF278H9J50ZSNM33P3JM1.my-token)
;; (define-constant y-token 'SP1QR3RAGH3GEME9WV7XB0TZCX6D5MNDQP97D35EH.my-token)
(define-public (add-to-position (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (token-swapr-trait <swapr-token>) (x uint) (y uint))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap-panic (map-get? pairs-data-map { token-x: token-x, token-y: token-y })))
(contract-address (as-contract tx-sender))
(recipient-address tx-sender)
(balance-x (get balance-x pair))
(balance-y (get balance-y pair))
(new-shares
(if (is-eq (get shares-total pair) u0)
(sqrti (* x y)) ;; burn a fraction of initial lp token to avoid attack as described in WP https://uniswap.org/whitepaper.pdf
(/ (* x (get shares-total pair)) balance-x)
)
)
;; TODO(psq): need to calculate y based on x, and only transfer the correct amount
;; without this, people could game the pool by only providing x!!! not nice...
(new-y
(if (is-eq (get shares-total pair) u0)
y
(/ (* x balance-y) balance-x)
)
)
(pair-updated (merge pair {
shares-total: (+ new-shares (get shares-total pair)),
balance-x: (+ balance-x x),
balance-y: (+ balance-y new-y)
}))
)
;; TODO(psq) check if x or y is 0, to calculate proper exchange rate unless shares-total is 0, which would be an error
(asserts! (is-ok (contract-call? token-x-trait transfer x tx-sender contract-address)) transfer-x-failed-err)
(asserts! (is-ok (contract-call? token-y-trait transfer new-y tx-sender contract-address)) transfer-y-failed-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-updated)
(try! (contract-call? token-swapr-trait mint recipient-address new-shares))
(print { object: "pair", action: "liquidity-added", data: pair-updated })
(ok true)
)
)
(define-read-only (get-pair-details (token-x principal) (token-y principal))
(unwrap-panic (map-get? pairs-data-map { token-x: token-x, token-y: token-y }))
)
(define-read-only (get-pair-contracts (pair-id uint))
(unwrap-panic (map-get? pairs-map { pair-id: pair-id }))
)
(define-read-only (get-pair-count)
(ok (var-get pair-count))
)
;; (define-read-only (get-pairs)
;; (ok (map get-pair-contracts (var-get pairs-list)))
;; )
(define-public (create-pair (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (token-swapr-trait <swapr-token>) (pair-name (string-ascii 32)) (x uint) (y uint))
;; TOOD(psq): add creation checks, then create map before proceeding to add-to-position
;; check neither x,y or y,x exists`
(let
(
(name-x (unwrap-panic (contract-call? token-x-trait get-name)))
(name-y (unwrap-panic (contract-call? token-y-trait get-name)))
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair-id (+ (var-get pair-count) u1))
(pair-data {
shares-total: u0,
balance-x: u0,
balance-y: u0,
fee-balance-x: u0,
fee-balance-y: u0,
fee-to-address: none,
swapr-token: (contract-of token-swapr-trait),
name: pair-name,
})
)
(asserts!
(and
(is-none (map-get? pairs-data-map { token-x: token-x, token-y: token-y }))
(is-none (map-get? pairs-data-map { token-x: token-y, token-y: token-x }))
)
pair-already-exists-err
)
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-data)
(map-set pairs-map { pair-id: pair-id } { token-x: token-x, token-y: token-y })
;; (var-set pairs-list (unwrap! (as-max-len? (append (var-get pairs-list) pair-id) u2000) too-many-pairs-err))
(var-set pair-count pair-id)
(try! (add-to-position token-x-trait token-y-trait token-swapr-trait x y))
(print { object: "pair", action: "created", data: pair-data })
(ok true)
)
)
;; ;; reduce the amount of liquidity the sender provides to the pool
;; ;; to close, use u100
(define-public (reduce-position (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (token-swapr-trait <swapr-token>) (percent uint))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
(balance-x (get balance-x pair))
(balance-y (get balance-y pair))
(shares (unwrap-panic (contract-call? token-swapr-trait get-balance-of tx-sender)))
(shares-total (get shares-total pair))
(contract-address (as-contract tx-sender))
(sender tx-sender)
(withdrawal (/ (* shares percent) u100))
(withdrawal-x (/ (* withdrawal balance-x) shares-total))
(withdrawal-y (/ (* withdrawal balance-y) shares-total))
(pair-updated
(merge pair
{
shares-total: (- shares-total withdrawal),
balance-x: (- (get balance-x pair) withdrawal-x),
balance-y: (- (get balance-y pair) withdrawal-y)
}
)
)
)
(asserts! (<= percent u100) value-out-of-range-err)
(asserts! (is-ok (as-contract (contract-call? token-x-trait transfer withdrawal-x contract-address sender))) transfer-x-failed-err)
(asserts! (is-ok (as-contract (contract-call? token-y-trait transfer withdrawal-y contract-address sender))) transfer-y-failed-err)
;; (unwrap-panic (decrease-shares token-x token-y tx-sender withdrawal)) ;; should never fail, you know...
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-updated)
;; TODO(psq): use burn
;; (unwrap-panic (contract-call? token-swapr-trait transfer withdrawal tx-sender contract-address)) ;; transfer back to swapr, wish there was a burn instead...
(try! (contract-call? token-swapr-trait burn tx-sender withdrawal))
(print { object: "pair", action: "liquidity-removed", data: pair-updated })
(ok (list withdrawal-x withdrawal-y))
)
)
;; exchange known dx of x-token for whatever dy of y-token based on current liquidity, returns (dx dy)
;; the swap will not happen if can't get at least min-dy back
(define-public (swap-x-for-y (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (dx uint) (min-dy uint))
;; calculate dy
;; calculate fee on dx
;; transfer
;; update balances
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
(balance-x (get balance-x pair))
(balance-y (get balance-y pair))
(contract-address (as-contract tx-sender))
(sender tx-sender)
(dy (/ (* u997 balance-y dx) (+ (* u1000 balance-x) (* u997 dx)))) ;; overall fee is 30 bp, either all for the pool, or 25 bp for pool and 5 bp for operator
(fee (/ (* u5 dx) u10000)) ;; 5 bp
(pair-updated
(merge pair
{
balance-x: (+ (get balance-x pair) dx),
balance-y: (- (get balance-y pair) dy),
fee-balance-x: (if (is-some (get fee-to-address pair)) ;; only collect fee when fee-to-address is set
(+ fee (get fee-balance-x pair))
(get fee-balance-x pair))
}
)
)
)
(asserts! (< min-dy dy) too-much-slippage-err)
;; TODO(psq): check that the amount transfered in matches the amount requested
(asserts! (is-ok (contract-call? token-x-trait transfer dx sender contract-address)) transfer-x-failed-err)
(asserts! (is-ok (as-contract (contract-call? token-y-trait transfer dy contract-address sender))) transfer-y-failed-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-updated)
(print { object: "pair", action: "swap-x-for-y", data: pair-updated })
(ok (list dx dy))
)
)
;; exchange known dy for whatever dx based on liquidity, returns (dx dy)
;; the swap will not happen if can't get at least min-dx back
(define-public (swap-y-for-x (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>) (dy uint) (min-dx uint))
;; calculate dx
;; calculate fee on dy
;; transfer
;; update balances
(let ((token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
(balance-x (get balance-x pair))
(balance-y (get balance-y pair))
(contract-address (as-contract tx-sender))
(sender tx-sender)
;; check formula, vs x-for-y???
(dx (/ (* u997 balance-x dy) (+ (* u1000 balance-y) (* u997 dy)))) ;; overall fee is 30 bp, either all for the pool, or 25 bp for pool and 5 bp for operator
(fee (/ (* u5 dy) u10000)) ;; 5 bp
(pair-updated (merge pair {
balance-x: (- (get balance-x pair) dx),
balance-y: (+ (get balance-y pair) dy),
fee-balance-y: (if (is-some (get fee-to-address pair)) ;; only collect fee when fee-to-address is set
(+ fee (get fee-balance-y pair))
(get fee-balance-y pair))
})))
(asserts! (< min-dx dx) too-much-slippage-err)
;; TODO(psq): check that the amount transfered in matches the amount requested
(asserts! (is-ok (as-contract (contract-call? token-x-trait transfer dx contract-address sender))) transfer-x-failed-err)
(asserts! (is-ok (contract-call? token-y-trait transfer dy sender contract-address)) transfer-y-failed-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y } pair-updated)
(print { object: "pair", action: "swap-y-for-x", data: pair-updated })
(ok (list dx dy))
)
)
;; ;; activate the contract fee for swaps by setting the collection address, restricted to contract owner
(define-public (set-fee-to-address (token-x principal) (token-y principal) (address principal))
(let ((pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y }
{
shares-total: (get shares-total pair),
balance-x: (get balance-y pair),
balance-y: (get balance-y pair),
fee-balance-x: (get fee-balance-y pair),
fee-balance-y: (get fee-balance-y pair),
fee-to-address: (some address),
name: (get name pair),
swapr-token: (get swapr-token pair),
}
)
(ok true)
)
)
;; ;; clear the contract fee addres
;; ;; TODO(psq): if there are any collected fees, prevent this from happening, as the fees can no longer be collect with `collect-fees`
(define-public (reset-fee-to-address (token-x principal) (token-y principal))
(let ((pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
(asserts! (is-eq tx-sender contract-owner) not-owner-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y }
{
shares-total: (get shares-total pair),
balance-x: (get balance-x pair),
balance-y: (get balance-y pair),
fee-balance-x: (get fee-balance-y pair),
fee-balance-y: (get fee-balance-y pair),
fee-to-address: none,
name: (get name pair),
swapr-token: (get swapr-token pair),
}
)
(ok true)
)
)
;; ;; get the current address used to collect a fee
(define-read-only (get-fee-to-address (token-x principal) (token-y principal))
(let ((pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
(ok (get fee-to-address pair))
)
)
;; ;; get the amount of fees charged on x-token and y-token exchanges that have not been collected yet
(define-read-only (get-fees (token-x principal) (token-y principal))
(let ((pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err)))
(ok (list (get fee-balance-x pair) (get fee-balance-y pair)))
)
)
;; ;; send the collected fees the fee-to-address
(define-public (collect-fees (token-x-trait <sip-010-token>) (token-y-trait <sip-010-token>))
(let
(
(token-x (contract-of token-x-trait))
(token-y (contract-of token-y-trait))
(contract-address (as-contract tx-sender))
(pair (unwrap! (map-get? pairs-data-map { token-x: token-x, token-y: token-y }) invalid-pair-err))
(address (unwrap! (get fee-to-address pair) no-fee-to-address-err))
(fee-x (get fee-balance-x pair))
(fee-y (get fee-balance-y pair))
)
(asserts! (is-eq fee-x u0) no-fee-x-err)
(asserts! (is-ok (as-contract (contract-call? token-x-trait transfer fee-x contract-address address))) transfer-x-failed-err)
(asserts! (is-eq fee-y u0) no-fee-y-err)
(asserts! (is-ok (as-contract (contract-call? token-y-trait transfer fee-y contract-address address))) transfer-y-failed-err)
(map-set pairs-data-map { token-x: token-x, token-y: token-y }
{
shares-total: (get shares-total pair),
balance-x: (get balance-x pair),
balance-y: (get balance-y pair),
fee-balance-x: u0,
fee-balance-y: u0,
fee-to-address: (get fee-to-address pair),
name: (get name pair),
swapr-token: (get swapr-token pair),
}
)
(ok (list fee-x fee-y))
)
)
| 0xa37a51ba9151bcb3533472bf3c2bcb437944146e02802738fb9cfea8d00c6bd2 | 20,253 | success |
stx-token-v0a | ;; wrap the native STX token into an SRC20 compatible token to be usable along other tokens
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010-v0a.ft-trait)
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(begin
(ok (print (stx-get-balance owner)))
)
)
(define-read-only (get-total-supply)
(ok stx-liquid-supply)
)
;; returns the token name
(define-read-only (get-name)
(ok "STX")
)
(define-read-only (get-symbol)
(ok "STX")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6)
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/stx.json"))
)
;; {
;; "name":"STX",
;; "description":"STX token, as a SIP-010 compatible token",
;; "image":"https://swapr.finance/tokens/stx.png",
;; "vector":"https://swapr.finance/tokens/stx.svg"
;; }
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(stx-transfer? amount tx-sender recipient)
)
)
| 0x453a3c38d7257c05480e3032d265c18615e1e22ecc8b3dd5751f0abcae0069b5 | 20,255 | success |
plaid-token-v0a | ;; wrap the native STX token into an SRC20 compatible token to be usable along other tokens
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010-v0a.ft-trait)
(define-fungible-token plaid)
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance plaid owner))
)
;; returns the total number of tokens
;; TODO(psq): we don't have access yet, but once POX is available, this should be a value that
;; is available from Clarity
(define-read-only (get-total-supply)
(ok (ft-get-supply plaid))
)
;; returns the token name
(define-read-only (get-name)
(ok "Plaid")
)
(define-read-only (get-symbol)
(ok "PLD")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u8) ;; because we can, and interesting for testing wallets and other clients
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/plaid.json"))
)
;; {
;; "name":"Plaid",
;; "description":"Plaid token, used as a test token",
;; "image":"https://swapr.finance/tokens/plaid.png",
;; "vector":"https://swapr.finance/tokens/plaid.svg"
;; }
;; (transfer (uint principal principal) (response bool uint))
;; amount sender recipient
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(print "plaid.transfer")
(print amount)
(print tx-sender)
(print recipient)
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(print (ft-transfer? plaid amount tx-sender recipient))
)
)
;; TODO(psq): remove for mainnet, how???
(ft-mint? plaid u100000000000000 'SP3WZJAY2A398KKBT73M92PAGP5ZD2GE3JKC6KSSP)
(ft-mint? plaid u100000000 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF)
| 0xc9a7890a3cc0a9edf601bb3bab7e65be7236767ea1c11e209e7dd117ca142e1d | 20,257 | success |
plaid-stx-token-v0a | ;; ;; we implement the sip-010 + a mint function
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-trait-v0a.swapr-trait)
;; ;; we can use an ft-token here, so use it!
(define-fungible-token plaid-stx-token)
(define-constant no-acccess-err u40)
;; implement all functions required by sip-010
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(ft-transfer? plaid-stx-token amount tx-sender recipient)
)
)
(define-read-only (get-name)
(ok "Plaid STX swapr")
)
(define-read-only (get-symbol)
(ok "plaid-stx-swapr")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6) ;; arbitrary, or ok?
)
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance plaid-stx-token owner))
)
(define-read-only (get-total-supply)
(ok (ft-get-supply plaid-stx-token))
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/plaid-stx-token.json"))
)
;; {
;; "name":"Plaid-STX",
;; "description":"Plaid-STX swapr token",
;; "image":"https://swapr.finance/tokens/plaid-stx.png",
;; "vector":"https://swapr.finance/tokens/plaid-stx.svg"
;; }
;; one stop function to gather all the data relevant to the swapr token in one call
(define-read-only (get-data (owner principal))
(ok {
name: (unwrap-panic (get-name)),
symbol: (unwrap-panic (get-symbol)),
decimals: (unwrap-panic (get-decimals)),
uri: (unwrap-panic (get-token-uri)),
supply: (unwrap-panic (get-total-supply)),
balance: (unwrap-panic (get-balance-of owner))
})
)
;; the extra mint method used by swapr when adding liquidity
;; can only be used by swapr main contract
(define-public (mint (recipient principal) (amount uint))
(begin
(print "token-swapr.mint")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-v0a) (err no-acccess-err))
(ft-mint? plaid-stx-token amount recipient)
)
)
;; the extra burn method used by swapr when removing liquidity
;; can only be used by swapr main contract
(define-public (burn (recipient principal) (amount uint))
(begin
(print "token-swapr.burn")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-v0a) (err no-acccess-err))
(ft-burn? plaid-stx-token amount recipient)
)
)
| 0x42a0b19cb2a971afefaafad2d037123084ed890903a706bc98e4fe79c8acde7f | 20,258 | success |
thing-token-v0a | ;; wrap the native STX token into an SRC20 compatible token to be usable along other tokens
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010-v0a.ft-trait)
(define-fungible-token thing)
;; get the token balance of owner
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance thing owner))
)
;; returns the total number of tokens
;; TODO(psq): we don't have access yet, but once POX is available, this should be a value that
;; is available from Clarity
(define-read-only (get-total-supply)
(ok (ft-get-supply thing))
)
;; returns the token name
(define-read-only (get-name)
(ok "Thing")
)
(define-read-only (get-symbol)
(ok "THG")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u8) ;; because we can, and interesting for testing wallets and other clients
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/thing.json"))
)
;; {
;; "name":"Thing",
;; "description":"Thing token, used as a test token",
;; "image":"https://swapr.finance/tokens/thing.png",
;; "vector":"https://swapr.finance/tokens/thing.svg"
;; }
;; (transfer (uint principal principal) (response bool uint))
;; amount sender recipient
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(print "thing.transfer")
(print amount)
(print tx-sender)
(print recipient)
(asserts! (is-eq tx-sender sender) (err u255)) ;; too strict?
(print (ft-transfer? thing amount tx-sender recipient))
)
)
;; TODO(psq): remove for mainnet, how???
(ft-mint? thing u1000000000000 'SP3WZJAY2A398KKBT73M92PAGP5ZD2GE3JKC6KSSP)
| 0xfe046e409da60e9057e0b77d7454dde3800d134a614c702beae88438edee2d0f | 20,262 | success |
plaid-thing-token-v0a | ;; ;; we implement the sip-010 + a mint function
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-trait-v0a.swapr-trait)
;; ;; we can use an ft-token here, so use it!
(define-fungible-token plaid-thing-token)
(define-constant no-acccess-err u40)
;; implement all functions required by sip-010
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(ft-transfer? plaid-thing-token amount tx-sender recipient)
)
)
(define-read-only (get-name)
(ok "Plaid Thing swapr")
)
(define-read-only (get-symbol)
(ok "plaid-thing-swapr")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6) ;; arbitrary, or ok?
)
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance plaid-thing-token owner))
)
(define-read-only (get-total-supply)
(ok (ft-get-supply plaid-thing-token))
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/plaid-thing-token.json"))
)
;; {
;; "name":"Plaid-Thing",
;; "description":"Plaid-Thing swapr token",
;; "image":"https://swapr.finance/tokens/plaid-thing.png",
;; "vector":"https://swapr.finance/tokens/plaid-thing.svg"
;; }
;; one stop function to gather all the data relevant to the swapr token in one call
(define-read-only (get-data (owner principal))
(ok {
name: (unwrap-panic (get-name)),
symbol: (unwrap-panic (get-symbol)),
decimals: (unwrap-panic (get-decimals)),
uri: (unwrap-panic (get-token-uri)),
supply: (unwrap-panic (get-total-supply)),
balance: (unwrap-panic (get-balance-of owner))
})
)
;; the extra mint method used by swapr when adding liquidity
;; can only be used by swapr main contract
(define-public (mint (recipient principal) (amount uint))
(begin
(print "token-swapr.mint")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-v0a) (err no-acccess-err))
(ft-mint? plaid-thing-token amount recipient)
)
)
;; the extra burn method used by swapr when removing liquidity
;; can only be used by swapr main contract
(define-public (burn (recipient principal) (amount uint))
(begin
(print "token-swapr.burn")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-v0a) (err no-acccess-err))
(ft-burn? plaid-thing-token amount recipient)
)
)
| 0xcfd3be2333aa314ae119749bf7fcd442b1d1477bf4fcd613c54ad579f48d95d0 | 20,265 | success |
tokensoft-token-v0a | ;; Implement the `ft-trait` trait defined in the `ft-trait` contract - SIP 10
;; This can use sugared syntax in real deployment (unit tests do not allow)
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010-v0a.ft-trait)
;; ;; Implement the token restriction trait
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.restricted-token-trait-v0a.restricted-token-trait)
;; Error returned for permission denied - stolen from http 403
(define-constant PERMISSION_DENIED_ERROR u403)
;; Data variables specific to the deployed token contract
(define-data-var token-name (string-ascii 32) "")
(define-data-var token-symbol (string-ascii 32) "")
(define-data-var token-decimals uint u0)
;; Track who deployed the token and whether it has been initialized
(define-data-var deployer-principal principal tx-sender)
(define-data-var is-initialized bool false)
;; Meta Read Only Functions for reading details about the contract - conforms to SIP 10
;; --------------------------------------------------------------------------
;; Defines built in support functions for tokens used in this contract
;; A second optional parameter can be added here to set an upper limit on max total-supply
(define-fungible-token tokensoft-token)
;; Get the token balance of the specified owner in base units
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance tokensoft-token owner)))
;; Returns the token name
(define-read-only (get-name)
(ok (var-get token-name)))
;; Returns the symbol or "ticker" for this token
(define-read-only (get-symbol)
(ok (var-get token-symbol)))
;; Returns the number of decimals used
(define-read-only (get-decimals)
(ok (var-get token-decimals)))
;; Returns the total number of tokens that currently exist
(define-read-only (get-total-supply)
(ok (ft-get-supply tokensoft-token)))
;; Write function to transfer tokens between accounts - conforms to SIP 10
;; --------------------------------------------------------------------------
;; Transfers tokens to a recipient
;; The originator of the transaction (tx-sender) must be the 'sender' principal
;; Smart contracts can move tokens from their own address by calling transfer with the 'as-contract' modifier to override the tx-sender.
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(try! (detect-transfer-restriction amount sender recipient)) ;; Ensure there is no restriction
(asserts! (is-eq tx-sender sender) (err u4)) ;; Ensure the originator is the sender principal
(ft-transfer? tokensoft-token amount sender recipient))) ;; Transfer
;; Role Based Access Control
;; --------------------------------------------------------------------------
(define-constant OWNER_ROLE u0) ;; Can manage RBAC
(define-constant MINTER_ROLE u1) ;; Can mint new tokens to any account
(define-constant BURNER_ROLE u2) ;; Can burn tokens from any account
(define-constant REVOKER_ROLE u3) ;; Can revoke tokens and move them to any account
(define-constant BLACKLISTER_ROLE u4) ;; Can add principals to a blacklist that can prevent transfers
;; Each role will have a mapping of principal to boolean. A true "allowed" in the mapping indicates that the principal has the role.
;; Each role will have special permissions to modify or manage specific capabilities in the contract.
;; Note that adding/removing roles could be optimized by having just 1 function, but since this is sensitive functionality, it was split
;; into 2 separate functions to make it explicit.
;; See the Readme about more details on the RBAC setup.
(define-map roles { role: uint, account: principal } { allowed: bool })
;; Checks if an account has the specified role
(define-read-only (has-role (role-to-check uint) (principal-to-check principal))
(default-to false (get allowed (map-get? roles {role: role-to-check, account: principal-to-check}))))
;; Add a principal to the specified role
;; Only existing principals with the OWNER_ROLE can modify roles
(define-public (add-principal-to-role (role-to-add uint) (principal-to-add principal))
(begin
;; Check the contract-caller to verify they have the owner role
(asserts! (has-role OWNER_ROLE contract-caller) (err PERMISSION_DENIED_ERROR))
;; Print the action for any off chain watchers
(print { action: "add-principal-to-role", role-to-add: role-to-add, principal-to-add: principal-to-add })
(ok (map-set roles { role: role-to-add, account: principal-to-add } { allowed: true }))))
;; Remove a principal from the specified role
;; Only existing principals with the OWNER_ROLE can modify roles
;; WARN: Removing all owners will irrevocably lose all ownership permissions
(define-public (remove-principal-from-role (role-to-remove uint) (principal-to-remove principal))
(begin
;; Check the contract-caller to verify they have the owner role
(asserts! (has-role OWNER_ROLE contract-caller) (err PERMISSION_DENIED_ERROR))
;; Print the action for any off chain watchers
(print { action: "remove-principal-from-role", role-to-remove: role-to-remove, principal-to-remove: principal-to-remove })
(ok (map-set roles { role: role-to-remove, account: principal-to-remove } { allowed: false }))))
;; Token URI
;; --------------------------------------------------------------------------
;; Variable for URI storage
(define-data-var uri (string-utf8 256) u"https://swapr.finance/tokens/token-soft-xbtc.json")
;; Public getter for the URI
(define-read-only (get-token-uri)
(ok (some (var-get uri))))
;; Setter for the URI - only the owner can set it
(define-public (set-token-uri (updated-uri (string-utf8 256)))
(begin
(asserts! (has-role OWNER_ROLE contract-caller) (err PERMISSION_DENIED_ERROR))
;; Print the action for any off chain watchers
(print { action: "set-token-uri", updated-uri: updated-uri })
(ok (var-set uri updated-uri))))
;; Minting and Burning
;; --------------------------------------------------------------------------
;; Mint tokens to the target address
;; Only existing principals with the MINTER_ROLE can mint tokens
(define-public (mint-tokens (mint-amount uint) (mint-to principal) )
(begin
(asserts! (has-role MINTER_ROLE contract-caller) (err PERMISSION_DENIED_ERROR))
;; Print the action for any off chain watchers
(print { action: "mint-tokens", mint-amount: mint-amount, mint-to: mint-to })
(ft-mint? tokensoft-token mint-amount mint-to)))
;; Burn tokens from the target address
;; Only existing principals with the BURNER_ROLE can mint tokens
(define-public (burn-tokens (burn-amount uint) (burn-from principal) )
(begin
(asserts! (has-role BURNER_ROLE contract-caller) (err PERMISSION_DENIED_ERROR))
;; Print the action for any off chain watchers
(print { action: "burn-tokens", burn-amount: burn-amount, burn-from : burn-from })
(ft-burn? tokensoft-token burn-amount burn-from)))
;; Revoking Tokens
;; --------------------------------------------------------------------------
;; Moves tokens from one account to another
;; Only existing principals with the REVOKER_ROLE can revoke tokens
(define-public (revoke-tokens (revoke-amount uint) (revoke-from principal) (revoke-to principal) )
(begin
(asserts! (has-role REVOKER_ROLE contract-caller) (err PERMISSION_DENIED_ERROR))
;; Print the action for any off chain watchers
(print { action: "revoke-tokens", revoke-amount: revoke-amount, revoke-from: revoke-from, revoke-to: revoke-to })
(ft-transfer? tokensoft-token revoke-amount revoke-from revoke-to)))
;; Blacklisting Principals
;; --------------------------------------------------------------------------
;; Blacklist mapping. If an account has blacklisted = true then no transfers in or out are allowed
(define-map blacklist { account: principal } { blacklisted: bool })
;; Checks if an account is blacklisted
(define-read-only (is-blacklisted (principal-to-check principal))
(default-to false (get blacklisted (map-get? blacklist { account: principal-to-check }))))
;; Updates an account's blacklist status
;; Only existing principals with the BLACKLISTER_ROLE can update blacklist status
(define-public (update-blacklisted (principal-to-update principal) (set-blacklisted bool))
(begin
(asserts! (has-role BLACKLISTER_ROLE contract-caller) (err PERMISSION_DENIED_ERROR))
;; Print the action for any off chain watchers
(print { action: "update-blacklisted", principal-to-update: principal-to-update, set-blacklisted: set-blacklisted })
(ok (map-set blacklist { account: principal-to-update } { blacklisted: set-blacklisted }))))
;; Transfer Restrictions
;; --------------------------------------------------------------------------
(define-constant RESTRICTION_NONE u0) ;; No restriction detected
(define-constant RESTRICTION_BLACKLIST u1) ;; Sender or receiver is on the blacklist
;; Checks to see if a transfer should be restricted. If so returns an error code that specifies restriction type.
(define-read-only (detect-transfer-restriction (amount uint) (sender principal) (recipient principal))
(if (or (is-blacklisted sender) (is-blacklisted recipient))
(err RESTRICTION_BLACKLIST)
(ok RESTRICTION_NONE)))
;; Returns the user viewable string for a specific transfer restriction
(define-read-only (message-for-restriction (restriction-code uint))
(if (is-eq restriction-code RESTRICTION_NONE)
(ok "No Restriction Detected")
(if (is-eq restriction-code RESTRICTION_BLACKLIST)
(ok "Sender or recipient is on the blacklist and prevented from transacting")
(ok "Unknown Error Code"))))
;; Initialization
;; --------------------------------------------------------------------------
;; Check to ensure that the same account that deployed the contract is initializing it
;; Only allow this funtion to be called once by checking "is-initialized"
(define-public (initialize (name-to-set (string-ascii 32)) (symbol-to-set (string-ascii 32) ) (decimals-to-set uint) (initial-owner principal))
(begin
(asserts! (is-eq tx-sender (var-get deployer-principal)) (err PERMISSION_DENIED_ERROR))
(asserts! (not (var-get is-initialized)) (err PERMISSION_DENIED_ERROR))
(var-set is-initialized true) ;; Set to true so that this can't be called again
(var-set token-name name-to-set)
(var-set token-symbol symbol-to-set)
(var-set token-decimals decimals-to-set)
(map-set roles { role: OWNER_ROLE, account: initial-owner } { allowed: true })
(ok true)))
;; TODO(psq): remove for mainnet, how???
(initialize "xBTC" "xBTC" u8 'ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE)
(ft-mint? tokensoft-token u2500000000 'SP3WZJAY2A398KKBT73M92PAGP5ZD2GE3JKC6KSSP)
(ft-mint? tokensoft-token u1500000000 'SP3C9VW89DFE6HY6054Q5BN0XZWDFTWV8FPTGT8JK)
| 0x40720171cd6543feb77a2f0dbe12b59fe72becdbaa188d521714aa87a20a6999 | 20,267 | success |
tokensoft-stx-token-v0a | ;; ;; we implement the sip-010 + a mint function
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-trait-v0a.swapr-trait)
;; ;; we can use an ft-token here, so use it!
(define-fungible-token tokensoft-stx-token)
(define-constant no-acccess-err u40)
;; implement all functions required by sip-010
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(ft-transfer? tokensoft-stx-token amount tx-sender recipient)
)
)
(define-read-only (get-name)
(ok "xBTC STX swapr")
)
(define-read-only (get-symbol)
(ok "xbtc-stx-swapr")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6) ;; arbitrary, or ok?
)
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance tokensoft-stx-token owner))
)
(define-read-only (get-total-supply)
(ok (ft-get-supply tokensoft-stx-token))
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/tokensoft-stx-token.json"))
)
;; {
;; "name":"Plaid-Thing",
;; "description":"Plaid-Thing swapr token",
;; "image":"https://swapr.finance/tokens/plaid-thing.png",
;; "vector":"https://swapr.finance/tokens/plaid-thing.svg"
;; }
;; one stop function to gather all the data relevant to the swapr token in one call
(define-read-only (get-data (owner principal))
(ok {
name: (unwrap-panic (get-name)),
symbol: (unwrap-panic (get-symbol)),
decimals: (unwrap-panic (get-decimals)),
uri: (unwrap-panic (get-token-uri)),
supply: (unwrap-panic (get-total-supply)),
balance: (unwrap-panic (get-balance-of owner))
})
)
;; the extra mint method used by swapr when adding liquidity
;; can only be used by swapr main contract
(define-public (mint (recipient principal) (amount uint))
(begin
(print "token-swapr.mint")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-v0a) (err no-acccess-err))
(ft-mint? tokensoft-stx-token amount recipient)
)
)
;; the extra burn method used by swapr when removing liquidity
;; can only be used by swapr main contract
(define-public (burn (recipient principal) (amount uint))
(begin
(print "token-swapr.burn")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-v0a) (err no-acccess-err))
(ft-burn? tokensoft-stx-token amount recipient)
)
)
| 0x49f34187be3caec3c3c50866ca0b663be67c3b77de19b8b6795f96c856cc8452 | 20,268 | success |
micro-nthng-v0 | (define-fungible-token micro-nothing)
(define-data-var total-supply uint u0)
(define-read-only (get-total-supply)
(var-get total-supply))
(define-private (mint! (account principal) (amount uint))
(if (<= amount u0)
(err u0)
(begin
(var-set total-supply (+ (var-get total-supply) amount))
(ft-mint? micro-nothing amount account))))
(define-public (transfer (to principal) (amount uint))
(if
(> (ft-get-balance micro-nothing tx-sender) u0)
(ft-transfer? micro-nothing amount tx-sender to)
(err u0)))
(mint! 'SP1AWFMSB3AGMFZY9JBWR9GRWR6EHBTMVA9JW4M20 u20000000000000)
(mint! 'SP1K1A1PMGW2ZJCNF46NWZWHG8TS1D23EGH1KNK60 u20000000000000)
(mint! 'SP2F2NYNDDJTAXFB62PJX351DCM4ZNEVRYJSC92CT u20000000000000)
(mint! 'SP32AEEF6WW5Y0NMJ1S8SBSZDAY8R5J32NBZFPKKZ u20000000000000)
(mint! 'SPT9JHCME25ZBZM9WCGP7ZN38YA82F77YM5HM08B u20000000000000)
(mint! 'SP3WZJAY2A398KKBT73M92PAGP5ZD2GE3JKC6KSSP u100000000000000)
(mint! 'ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE u100000000000000)
| 0x7ba4d47b734b7d39ace9b753b100574df6526f63ea53f7a6bd802a4165c82ef3 | 20,269 | success |
wrapped-nothing-v0 | (define-constant ERR-UNAUTHORIZED u1)
(define-constant ERR-YOU-POOR u2)
(define-fungible-token wrapped-nthng)
(define-data-var token-uri (optional (string-utf8 256)) none)
(define-constant contract-creator tx-sender)
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.sip-010-v0a.ft-trait)
(define-public (donate (amount uint))
(stx-transfer? amount tx-sender contract-creator))
(define-public (wrap-nthng (amount uint))
(if
(is-ok
(contract-call? .micro-nthng-v0 transfer (as-contract tx-sender) amount))
(begin
(ft-mint?
wrapped-nthng amount tx-sender)
)
(err ERR-YOU-POOR)))
(define-public (unwrap (amount uint))
(if
(is-ok (ft-burn? wrapped-nthng amount tx-sender))
(let ((unwrapper tx-sender))
(as-contract (contract-call? .micro-nthng-v0 transfer unwrapper amount)))
(err ERR-YOU-POOR)
))
;;;;;;;;;;;;;;;;;;;;; SIP 010 ;;;;;;;;;;;;;;;;;;;;;;
(define-public (transfer (amount uint) (from principal) (to principal))
(begin
(asserts! (is-eq from tx-sender)
(err ERR-UNAUTHORIZED))
(ft-transfer? wrapped-nthng amount from to)
)
)
(define-read-only (get-name)
(ok "Wrapped Nothing"))
(define-read-only (get-symbol)
(ok "WMNO"))
(define-read-only (get-decimals)
(ok u0))
(define-read-only (get-balance-of (user principal))
(ok (ft-get-balance wrapped-nthng user)))
(define-read-only (get-total-supply)
(ok (ft-get-supply wrapped-nthng)))
(define-public (set-token-uri (value (string-utf8 256)))
(if
(is-eq tx-sender contract-creator)
(ok (var-set token-uri (some value)))
(err ERR-UNAUTHORIZED)))
(define-read-only (get-token-uri)
(ok (var-get token-uri)))
;; send-many\
(define-public (send-nothing (amount uint) (to principal))
(let ((transfer-ok (try! (transfer amount tx-sender to))))
(ok transfer-ok)))
(define-private (send-nothing-unwrap (recipient { to: principal, amount: uint }))
(send-nothing
(get amount recipient)
(get to recipient)))
(define-private (check-err (result (response bool uint))
(prior (response bool uint)))
(match prior ok-value result
err-value (err err-value)))
(define-public (send-many (recipients (list 200 { to: principal, amount: uint })))
(fold check-err
(map send-nothing-unwrap recipients)
(ok true)))
(define-constant wrap-amount u50000000000000)
;; TODO(psq): doesn't work, probably because not funding the right thing, but ok because just minting will provide balance
;; (if
;; (is-ok (contract-call? .micro-nthng-v0 transfer 'SP3WZJAY2A398KKBT73M92PAGP5ZD2GE3JKC6KSSP wrap-amount))
;; (ft-mint? wrapped-nthng wrap-amount 'SP3WZJAY2A398KKBT73M92PAGP5ZD2GE3JKC6KSSP)
;; (err ERR-YOU-POOR)
;; )
(ft-mint? wrapped-nthng wrap-amount 'SP3WZJAY2A398KKBT73M92PAGP5ZD2GE3JKC6KSSP)
(set-token-uri u"https://swapr.finance/tokens/wrapped-nothing.json")
| 0xf5c50864d755ec26cdad1bc0b19deb7067ed042dc581b5381219f5f8ad1e0281 | 20,270 | success |
plaid-wmno-token-v0 | ;; ;; we implement the sip-010 + a mint function
(impl-trait 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-trait-v0a.swapr-trait)
;; ;; we can use an ft-token here, so use it!
(define-fungible-token plaid-wrapped-nothing-token)
(define-constant no-acccess-err u40)
;; implement all functions required by sip-010
(define-public (transfer (amount uint) (sender principal) (recipient principal))
(begin
(ft-transfer? plaid-wrapped-nothing-token amount tx-sender recipient)
)
)
(define-read-only (get-name)
(ok "Plaid Nothing swapr")
)
(define-read-only (get-symbol)
(ok "plaid-wmno-swapr")
)
;; the number of decimals used
(define-read-only (get-decimals)
(ok u6) ;; arbitrary, or ok?
)
(define-read-only (get-balance-of (owner principal))
(ok (ft-get-balance plaid-wrapped-nothing-token owner))
)
(define-read-only (get-total-supply)
(ok (ft-get-supply plaid-wrapped-nothing-token))
)
(define-read-only (get-token-uri)
(ok (some u"https://swapr.finance/tokens/plaid-wrapped-nothing-token.json"))
)
;; {
;; "name":"Plaid-STX",
;; "description":"Plaid-STX swapr token",
;; "image":"https://swapr.finance/tokens/plaid-stx.png",
;; "vector":"https://swapr.finance/tokens/plaid-stx.svg"
;; }
;; one stop function to gather all the data relevant to the swapr token in one call
(define-read-only (get-data (owner principal))
(ok {
name: (unwrap-panic (get-name)),
symbol: (unwrap-panic (get-symbol)),
decimals: (unwrap-panic (get-decimals)),
uri: (unwrap-panic (get-token-uri)),
supply: (unwrap-panic (get-total-supply)),
balance: (unwrap-panic (get-balance-of owner))
})
)
;; the extra mint method used by swapr when adding liquidity
;; can only be used by swapr main contract
(define-public (mint (recipient principal) (amount uint))
(begin
(print "token-swapr.mint")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-v0a) (err no-acccess-err))
(ft-mint? plaid-wrapped-nothing-token amount recipient)
)
)
;; the extra burn method used by swapr when removing liquidity
;; can only be used by swapr main contract
(define-public (burn (recipient principal) (amount uint))
(begin
(print "token-swapr.burn")
(print contract-caller)
(print amount)
(asserts! (is-eq contract-caller 'SP23DAB333A5CPFXNK13E5YMX1DZJ07112QNZEBCF.swapr-v0a) (err no-acccess-err))
(ft-burn? plaid-wrapped-nothing-token amount recipient)
)
)
| 0xccb28faf171d5de3c118de21ab650bb8ec8a99e2c38769e7c78d66a9dca8c883 | 20,272 | success |
BNS-migrated-helper | (define-read-only (get-migrated-names (owner principal))
(at-block (unwrap-panic (get-block-info? id-header-hash u1)) (contract-call? 'SP000000000000000000002Q6VF78.bns resolve-principal owner))
) | 0x9c2ccd442df1b2ffc09b7948f58f0cc263fd24d9af71e48e3c56d1f9fc1dd635 | 21,305 | success |
fari-token | (define-trait sip-010-trait
(
;; Transfer from the caller to a new principal
(transfer (uint principal principal (optional (buff 34))) (response bool uint))
;; the human readable name of the token
(get-name () (response (string-ascii 32) uint))
;; the ticker symbol, or empty if none
(get-symbol () (response (string-ascii 32) uint))
;; the number of decimals used, e.g. 6 would mean 1_000_000 represents 1 token
(get-decimals () (response uint uint))
;; the balance of the passed principal
(get-balance (principal) (response uint uint))
;; the current total supply (which does not need to be a constant)
(get-total-supply () (response uint uint))
;; an optional URI that represents metadata of this token
(get-token-uri () (response (optional (string-utf8 256)) uint))
)
)
(define-fungible-token fari-token)
;; get the token balance of owner
(define-read-only (get-balance (owner principal))
(begin
(ok (ft-get-balance fari-token owner))))
;; returns the total number of tokens
(define-read-only (get-total-supply)
(ok (ft-get-supply fari-token)))
;; returns the token name
(define-read-only (get-name)
(ok "Fari Token"))
;; the symbol or "ticker" for this token
(define-read-only (get-symbol)
(ok "FARI"))
;; the number of decimals used
(define-read-only (get-decimals)
(ok u8))
;; Transfers tokens to a recipient
(define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34))))
(if (is-eq tx-sender sender)
(begin
(try! (ft-transfer? fari-token amount sender recipient))
(print memo)
(ok true)
)
(err u4)))
(define-public (get-token-uri)
(ok (some u"https://www.bitfari.org/token/")))
;; Mint this token to a few people when deployed
;; development team
(ft-mint? fari-token u10000000 'SP3SW54K3QMDZ0BB34KXQ62FNFKDBYB4RMTHJ19SG)
;; bitfari foundation treasury
;; 10% to be distributed to the community for development, promotions, etc.
;; 90% reserved for network operation, distributed programmatically to screen operators, auditors, customers, etc.
(ft-mint? fari-token u90000000 'SP213KNHB5QD308TEESY1ZMX1BP8EZDPG4JWD0MEA) | 0xd9d18a8210603ada8f0b231cea636ea37975fa55b769b7b137b22eb483f26aa1 | 21,360 | success |
stxpredict_v5 | ;; This is stxpredict - A prediction market on Stacks - v5
;; Create a new market by sending description, resolver account, resolve type: auto or manual and resolve date/time.
;; Once resolve date/time has passed, resolver can call resolveMarket with the final result. Users will manually exit markets.
;; For Auto resolve markets, user can ping oracle to request resolution of the market.
;; Limitations: Only yes/no questions, static payment per vote, one account can join only one side, Auto-resolve markets can only be defined as higher, No fees for oracle (yet), traits WIP
(define-map marketDatabase {marketId: int} {question: (string-ascii 99), threshold: int, balance: uint, paypervote: uint, resolver: principal, yescount: uint, nocount: uint, resolveTime: uint, resolveType: (string-ascii 10), resolved: bool, result: bool})
;; voters db
(define-map yesvoters {marketId: int, voter: principal} {amount: uint})
(define-map novoters {marketId: int, voter: principal} {amount: uint})
(define-data-var numberOfMarkets int 0)
;; increment marketId
(define-private (incrementMarketId)
(begin
(var-set numberOfMarkets (+ (var-get numberOfMarkets) 1))
(var-get numberOfMarkets)
)
)
;; trait for oracle autoresolve
(define-trait prediction-market-oracle
(
;; oracle shall accept requests from users to resolve markets
(requestResolution (int) (response bool uint))
;; oracle shall read threshold value from market
(readMarketThreshold (int) (response int uint))
;; oracle shall resolve markets
(resolveMarket (int bool) (response bool uint))
)
)
;; public functions
;; create a new prediction market
(define-public (createMarket (question (string-ascii 99)) (threshold int) (paypervote uint) (resolver principal) (resolveTime uint) (resolveType (string-ascii 10)))
(begin
(map-set marketDatabase {marketId: (incrementMarketId)} {question: question, threshold: threshold, balance: u0, paypervote: paypervote, resolver: resolver, yescount: u0, nocount: u0, resolveTime: resolveTime, resolveType: resolveType, resolved: false, result: false})
(ok "Prediction market created")
)
)
(define-public (joinMarket (marketId int) (side bool) (amount uint))
(let (
(validMarketId (<= marketId (var-get numberOfMarkets)))
(resolved (getResolved marketId))
(validAmount (>= amount (default-to u1 (get paypervote (map-get? marketDatabase {marketId: marketId})))))
)
(if (and validMarketId (not resolved) validAmount)
(begin
(if side (map-insert yesvoters {marketId: marketId, voter: tx-sender} {amount: amount}) (map-insert novoters {marketId: marketId, voter: tx-sender} {amount: amount}))
(addBalance marketId tx-sender amount)
(incrementCount marketId side)
)
(err u2)
)
)
)
(define-public (resolveMarket (marketId int) (result bool))
(let (
(resolved (getResolved marketId))
(timeToResolve (check-time-to-resolve marketId))
(resolver (default-to 'SP15RGYVK9ACFQWMFFA2TVASDVZH38B4VATY8CJ01 (get resolver (map-get? marketDatabase {marketId: marketId}))))
)
(if (and (not resolved) timeToResolve (is-eq resolver tx-sender))
(ok (setResult marketId result))
(ok false)
)
)
)
(define-public (exitMarket (marketId int))
(let (
(resolved (getResolved marketId))
(result (getResult marketId))
(vote (getVote marketId))
(payout (getPayout marketId))
)
(if (and resolved vote)
(stx-transfer? payout (as-contract tx-sender) tx-sender)
(err u2)
)
)
)
;; helpers/private functions
;; get threshold of a market - for oracle usage
(define-read-only (readMarketThreshold (marketId int))
(ok (get threshold (map-get? marketDatabase {marketId: marketId})))
)
;; add stx to the contract
(define-private (addBalance (marketId int) (participant principal) (amount uint))
(begin
(unwrap-panic (stx-transfer? amount participant (as-contract tx-sender)))
(match
(map-get? marketDatabase {marketId: marketId})
market
(map-set marketDatabase {marketId: marketId} (merge market {balance: (+ (default-to u0 (get balance (map-get? marketDatabase {marketId: marketId}))) amount)}))
false
)
)
)
;; get balance of marketId
(define-private (getBalance (marketId int))
(default-to u0 (get balance (map-get? marketDatabase {marketId: marketId})))
)
;; get resolveTime of marketId
(define-private (getResolveTime (marketId int))
(default-to u2147483647 (get resolveTime (map-get? marketDatabase {marketId: marketId})))
)
;; get payout of marketId, calculate payout = divide market balance by # of winning votes
(define-private (getPayout (marketId int))
(if (unwrap-panic (get result (map-get? marketDatabase {marketId: marketId})))
(let ((count (default-to u1 (get yescount (map-get? marketDatabase {marketId: marketId})))) (balance (getBalance marketId))) (print count) (print balance) (/ balance count))
(let ((count (default-to u1 (get nocount (map-get? marketDatabase {marketId: marketId})))) (balance (getBalance marketId))) (print count) (print balance) (/ balance count))
)
)
;; check if user voted for a marketId same as resolved
(define-private (getVote (marketId int))
(if (unwrap-panic (get result (map-get? marketDatabase {marketId: marketId})))
(is-some (map-get? yesvoters {marketId: marketId, voter: tx-sender}))
(is-some (map-get? novoters {marketId: marketId, voter: tx-sender}))
)
)
;; check if market resolved
(define-private (getResolved (marketId int))
(if (unwrap-panic (get resolved (map-get? marketDatabase {marketId: marketId})))
(print true)
(print false)
)
)
;; get market result - not really needed - public for informational purposes
(define-private (getResult (marketId int))
(if (unwrap-panic (get result (map-get? marketDatabase {marketId: marketId})))
(print true)
(print false)
)
)
(define-private (setResult (marketId int) (result bool))
(match
(map-get? marketDatabase {marketId: marketId})
market
(map-set marketDatabase {marketId: marketId}
(merge market { result: result, resolved: true })
)
false
)
)
;; add 1 to yescount/nocount depending on which side user took for this market
(define-private (incrementCount (marketId int) (side bool))
(begin
(match
(map-get? marketDatabase {marketId: marketId})
market
(if side
(map-set marketDatabase {marketId: marketId} (merge market {yescount: (+ (default-to u0 (get yescount (map-get? marketDatabase {marketId: marketId}))) u1)}))
(map-set marketDatabase {marketId: marketId} (merge market {nocount: (+ (default-to u0 (get nocount (map-get? marketDatabase {marketId: marketId}))) u1)}))
)
false
)
(ok u8)
)
)
;; utils
;; get time from current block
(define-private (get-current-block-time)
(default-to u0 (get-block-info? time block-height)))
;; get if resolve time has passed
(define-private (check-time-to-resolve (marketId int))
(if (>= (get-current-block-time) (getResolveTime marketId))
true
false
)
)
| 0x4dbac2af76da1e1e6078fe6cdaf871258223863cd0bb3165b738e20ab90d6f38 | 21,379 | success |
resolver_v1_coinbase_btc | (define-constant openOracleSource "coinbase")
(define-constant openOracleSymbol "BTC")
(define-read-only (readMarketThreshold (marketId int))
(begin
(contract-call? 'SP15RGYVK9ACFQWMFFA2TVASDVZH38B4VATY8CJ01.stxpredict_v5 readMarketThreshold marketId)
)
)
;; public function for a user to call to request resolution of a market
(define-public (requestResolution (marketId int))
(let (
(result (unwrap-panic (decideResolution marketId)))
(currentvalue (to-int (unwrap-panic (get amount (getOraclePrice)))))
)
(if (is-eq result true)
(ok (resolveMarket marketId result))
(ok (resolveMarket marketId result))
)
)
)
(define-private (decideResolution (marketId int))
(let (
(threshold (default-to 0 (unwrap-panic (readMarketThreshold marketId))))
(currentvalue (to-int (unwrap-panic (get amount (getOraclePrice)))))
)
(if (> currentvalue threshold)
(ok true)
(ok false)
)
)
)
(define-private (resolveMarket (marketId int) (result bool))
(begin
(contract-call? 'SP15RGYVK9ACFQWMFFA2TVASDVZH38B4VATY8CJ01.stxpredict_v5 resolveMarket marketId result)
)
)
;; psq signed oracle from exchanges
;; testnet STZ0RAC1EFTH949T4W2SYY6YBHJRMAF4ED5QB123.oracle-v1
;; mainnet SPZ0RAC1EFTH949T4W2SYY6YBHJRMAF4ECT5A7DD.oracle-v1
(define-private (getOraclePrice)
(contract-call? 'SPZ0RAC1EFTH949T4W2SYY6YBHJRMAF4ECT5A7DD.oracle-v1 get-price openOracleSource openOracleSymbol)
)
| 0x5e31c4f4f1e28601fae381cec30015e183d4f0e5eed73a9c5742d4fed8592a7a | 21,386 | success |
resolver_v1_coinbase_btc | (define-constant openOracleSource "coinbase")
(define-constant openOracleSymbol "BTC")
(define-read-only (readMarketThreshold (marketId int))
(begin
(contract-call? 'SP15RGYVK9ACFQWMFFA2TVASDVZH38B4VATY8CJ01.stxpredict_v5 readMarketThreshold marketId)
)
)
;; public function for a user to call to request resolution of a market
(define-public (requestResolution (marketId int))
(let (
(result (unwrap-panic (decideResolution marketId)))
(currentvalue (to-int (unwrap-panic (get amount (getOraclePrice)))))
)
(if (is-eq result true)
(ok (resolveMarket marketId result))
(ok (resolveMarket marketId result))
)
)
)
(define-private (decideResolution (marketId int))
(let (
(threshold (default-to 0 (unwrap-panic (readMarketThreshold marketId))))
(currentvalue (to-int (unwrap-panic (get amount (getOraclePrice)))))
)
(if (> currentvalue threshold)
(ok true)
(ok false)
)
)
)
(define-private (resolveMarket (marketId int) (result bool))
(begin
(contract-call? 'SP15RGYVK9ACFQWMFFA2TVASDVZH38B4VATY8CJ01.stxpredict_v5 resolveMarket marketId result)
)
)
;; psq signed oracle from exchanges
;; testnet STZ0RAC1EFTH949T4W2SYY6YBHJRMAF4ED5QB123.oracle-v1
;; mainnet SPZ0RAC1EFTH949T4W2SYY6YBHJRMAF4ECT5A7DD.oracle-v1
(define-private (getOraclePrice)
(contract-call? 'SPZ0RAC1EFTH949T4W2SYY6YBHJRMAF4ECT5A7DD.oracle-v1 get-price openOracleSource openOracleSymbol)
)
| 0x5e31c4f4f1e28601fae381cec30015e183d4f0e5eed73a9c5742d4fed8592a7a | 21,387 | success |